English 中文(简体)
我如何在iPhone上创建圆角UILabel?
原标题:
  • 时间:2009-02-04 07:19:49
  •  标签:

有内置的方法来创建圆角 UILabel 吗?如果答案是否定的,那么该如何创建这样一个对象呢?

最佳回答

iOS 3.0 and later

iPhone OS 3.0 及更高版本支持 CALayer 类上的 cornerRadius 属性。每个视图都有一个可以操作的 CALayer 实例。这意味着您可以通过一行代码实现圆角:

view.layer.cornerRadius = 8;

您需要导入#import <QuartzCore/QuartzCore.h>并链接到QuartzCore框架,以获取对CALayer的头文件和属性的访问权限。

Before iOS 3.0

其中一种方法,我最近使用的方法是创建一个UIView子类,它仅绘制一个圆角矩形,然后将UILabel或在我这种情况下是UITextView,作为它的子视图。具体来说:

  1. Create a UIView subclass and name it something like RoundRectView.
  2. In RoundRectView s drawRect: method, draw a path around the bounds of the view using Core Graphics calls like CGContextAddLineToPoint() for the edges and and CGContextAddArcToPoint() for the rounded corners.
  3. Create a UILabel instance and make it a subview of the RoundRectView.
  4. Set the frame of the label to be a few pixels inset of the RoundRectView s bounds. (For example, label.frame = CGRectInset(roundRectView.bounds, 8, 8);)

如果您创建一个通用的UIView,然后使用检查器(inspector)更改其类别,您可以使用界面生成器将RoundRectView放置在一个视图上。在编译和运行应用程序之前,你看不到矩形,但至少你能够放置子视图并根据需要连接到出口或操作。

问题回答

对于iOS 7.1或更高版本的设备,您需要添加:

yourUILabel.layer.masksToBounds = YES;
yourUILabel.layer.cornerRadius = 8.0;

基于 OScarsWyck 的答案,适用于 Swift IOS8 及以上版本:

yourUILabel.layer.masksToBounds = true
yourUILabel.layer.cornerRadius = 8.0
  1. you have an UILabel called: myLabel.
  2. in your "m" or "h" file import: #import <QuartzCore/QuartzCore.h>
  3. 在你的viewDidLoad中写入以下代码:self.myLabel.layer.cornerRadius = 8;

    • depends on how you want you can change cornerRadius value from 8 to other number :)

祝你好运 (zhù nǐ hǎo yùn)

你可以通过以下方法使任何控件的边框带有圆角和边框宽度:-

CALayer * l1 = [lblName layer];
[l1 setMasksToBounds:YES];
[l1 setCornerRadius:5.0];

// You can even add a border
[l1 setBorderWidth:5.0];
[l1 setBorderColor:[[UIColor darkGrayColor] CGColor]];


Just replace lblName with your UILabel.

Note:- Don t forget to import <QuartzCore/QuartzCore.h>

Swift 3

如果您想要带有背景颜色的圆形标签,除了其他大部分答案外,您还需要设置layer的背景颜色。当设置view背景颜色时,它无法正常工作。

label.layer.cornerRadius = 8
label.layer.masksToBounds = true
label.layer.backgroundColor = UIColor.lightGray.cgColor

如果您正在使用自动布局,希望在标签周围添加一些填充,并且不想手动设置标签的大小,则可以创建UILabel子类并覆盖intrinsicContentSize属性:

class LabelWithPadding: UILabel {
    override var intrinsicContentSize: CGSize {
        let defaultSize = super.intrinsicContentSize
        return CGSize(width: defaultSize.width + 12, height: defaultSize.height + 8)
    }
}

要将两者合并,您还需要设置label.textAlignment = center,否则文本将左对齐。

我制作了一个快速的UILabel子类来实现这个效果。此外,我会自动将文本颜色设置为黑色或白色,以获得最大对比度。

Result

将此翻译成中文:colors-rounded-borders 颜色圆角边框

使用的SO帖子:

Playground

只需将此粘贴到iOS Playground中:

//: Playground - noun: a place where people can play

import UIKit

class PillLabel : UILabel{

    @IBInspectable var color = UIColor.lightGrayColor()
    @IBInspectable var cornerRadius: CGFloat = 8
    @IBInspectable var labelText: String = "None"
    @IBInspectable var fontSize: CGFloat = 10.5

    // This has to be balanced with the number of spaces prefixed to the text
    let borderWidth: CGFloat = 3

    init(text: String, color: UIColor = UIColor.lightGrayColor()) {
        super.init(frame: CGRectMake(0, 0, 1, 1))
        labelText = text
        self.color = color
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup(){
        // This has to be balanced with the borderWidth property
        text = "  (labelText)".uppercaseString

        // Credits to https://stackoverflow.com/a/33015915/784318
        layer.borderWidth = borderWidth
        layer.cornerRadius = cornerRadius
        backgroundColor = color
        layer.borderColor = color.CGColor
        layer.masksToBounds = true
        font = UIFont.boldSystemFontOfSize(fontSize)
        textColor = color.contrastColor
        sizeToFit()

        // Credits to https://stackoverflow.com/a/15184257/784318
        frame = CGRectInset(self.frame, -borderWidth, -borderWidth)
    }
}


extension UIColor {
    // Credits to https://stackoverflow.com/a/29044899/784318
    func isLight() -> Bool{
        var green: CGFloat = 0.0, red: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0
        self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        let brightness = ((red * 299) + (green * 587) + (blue * 114) ) / 1000

        return brightness < 0.5 ? false : true
    }

    var contrastColor: UIColor{
        return self.isLight() ? UIColor.blackColor() : UIColor.whiteColor()
    }
}

var label = PillLabel(text: "yellow", color: .yellowColor())

label = PillLabel(text: "green", color: .greenColor())

label = PillLabel(text: "white", color: .whiteColor())

label = PillLabel(text: "black", color: .blackColor())

xCode 7.3.1 iOS 9.3.2 (请注意:由于“xCode”是专有名词,所以最好不要翻译它,直接使用罗马字。)

 _siteLabel.layer.masksToBounds = true;
  _siteLabel.layer.cornerRadius = 8;

If you want rounded corner of UI objects like (UILabel, UIView, UIButton, UIImageView) by storyboard then set clip to bounds true and set User Defined Runtime Attributes Key path as layer.cornerRadius, type = Number and value = 9 (as your requirement)

Set clip to bounds as Set User Defined Runtime Attributes as

另一种方法是将png放置在UILabel后面。我有几个视图,其中涵盖了一个单一背景png,其中包含了各个标签的所有艺术品。

在 Xcode 8.1.2 和 Swift 3 中运行良好。

.cornerRadius是设置圆角边缘的关键属性。如果您在应用程序中对所有标签使用相同的样式,我建议使用扩展方法。

代码:

 // extension Class
extension UILabel {

    // extension user defined Method
    func setRoundEdge() {
        let myGreenColor = (UIColor(red: -0.108958, green: 0.714926, blue: 0.758113, alpha: 1.0))
        //Width of border
        self.layer.borderWidth = 1.0
        //How much the edge to be rounded
        self.layer.cornerRadius = 5.0

        // following properties are optional
        //color for border
        self.layer.borderColor = myGreenColor.cgColor
        //color for text
        self.textColor = UIColor.red
        // Mask the bound
        self.layer.masksToBounds = true
        //clip the pixel contents
        self.clipsToBounds = true
    }
}

输出:

将此翻译成中文:输入图片说明

为什么需要扩展方法?

创建一个Swift文件并添加以下代码,这个扩展方法针对“UILabel”类,这个方法是用户定义的,但对于应用程序中的所有标签都有作用,并且有助于保持一致性和清洁代码,如果您将来需要更改任何样式,只需要在扩展方法中进行修改即可。

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    label.text = @"Your String.";
    label.layer.cornerRadius = 8.0;
    [self.view addSubview:label];

在Monotouch / Xamarin.iOS中,我是这样解决相同的问题的:

UILabel exampleLabel = new UILabel(new CGRect(0, 0, 100, 50))
        {
            Text = "Hello Monotouch red label"
        };
        exampleLabel.Layer.MasksToBounds = true;
        exampleLabel.Layer.CornerRadius = 8;
        exampleLabel.Layer.BorderColor = UIColor.Red.CGColor;
        exampleLabel.Layer.BorderWidth = 2;

在Swift 2.0中完美运作。

    @IBOutlet var theImage: UIImageView! //you can replace this with any UIObject eg: label etc


    override func viewDidLoad() {
        super.viewDidLoad()
//Make sure the width and height are same
        self.theImage.layer.cornerRadius = self.theImage.frame.size.width / 2
        self.theImage.layer.borderWidth = 2.0
        self.theImage.layer.borderColor = UIColor.whiteColor().CGColor
        self.theImage.clipsToBounds = true

    }

你试过使用来自Interface Builder的UIButton(它有圆角),并尝试使用设置将其看起来像一个标签。如果你只想显示静态文本。

根据您要做的具体操作,您可以通过编程创建图像并将其设为背景。





相关问题
热门标签