如何在iPhone上创建圆角UILabel?

时间:2009-02-04 07:19:49

标签: ios objective-c cocoa-touch uilabel rounded-corners

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

16 个答案:

答案 0 :(得分:227)

iOS 3.0及更高版本

iPhone OS 3.0及更高版本支持cornerRadius类的CALayer属性。每个视图都有一个CALayer实例,您可以操作它。这意味着您可以在一行中获得圆角:

view.layer.cornerRadius = 8;

您需要#import <QuartzCore/QuartzCore.h>并链接到QuartzCore框架才能访问CALayer的标题和属性。

在iOS 3.0之前

我最近使用的一种方法是创建一个UIView子类,它只是绘制一个圆角矩形,然后制作UILabel,或者在我的情况下,UITextView,它内部的子视图。具体做法是:

  1. 创建一个UIView子类,并将其命名为RoundRectView
  2. RoundRectView的{​​{1}}方法中,使用Core Graphics调用(如边缘的CGContextAddLineToPoint()和圆角的CGContextAddArcToPoint())绘制视图边界周围的路径。
  3. 创建一个drawRect:实例,并将其作为RoundRectView的子视图。
  4. 将标签的框架设置为RoundRectView边界的几个像素插入。 (例如,UILabel
  5. 如果您创建了一个通用的UIView,然后使用检查器更改其类,则可以使用Interface Builder将RoundRectView放置在视图上。在编译和运行应用程序之前,您不会看到矩形,但至少您可以放置​​子视图并将其连接到出口或操作(如果需要)。

答案 1 :(得分:136)

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

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

答案 2 :(得分:19)

对于Swift IOS8以后的OScarsWyck回答:

yourUILabel.layer.masksToBounds = true
yourUILabel.layer.cornerRadius = 8.0

答案 3 :(得分:11)

  1. 您有一个名为UILabel的{​​{1}}。
  2. 在您的“m”或“h”文件中导入:myLabel
  3. {li>

    #import <QuartzCore/QuartzCore.h>中写下这一行:viewDidLoad

    • 取决于您希望如何将cornerRadius值从8更改为其他数字:)
    祝你好运

答案 4 :(得分:11)

您可以这样使用任何控件的边框宽度制作圆角边框: -

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]];


只需将lblName替换为UILabel即可。

注意: - 不要忘记导入<QuartzCore/QuartzCore.h>

答案 5 :(得分:6)

另一种方法是在UILabel后面放置一个png。我有几个标签的视图,这些标签覆盖了单个背景png,其中包含各个标签的所有图稿。

答案 6 :(得分:6)

xCode 7.3.1 iOS 9.3.2

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

答案 7 :(得分:5)

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

结果

colors-rounded-borders

二手SO-Posts:

游乐场

只需将其粘贴到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())

答案 8 :(得分:4)

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

答案 9 :(得分:3)

如果您希望通过故事板将(例如UILabelUIViewUIButtonUIImageView)等UI对象的圆角设置为clip to bounds,则设置{ {1}}密钥路径为 User Defined Runtime Attributes,类型=数字和值= 9(根据您的要求)

Set clip to bounds as Set User Defined Runtime Attributes as

答案 10 :(得分:2)

您是否尝试使用“界面”构建器中的UIButton(具有圆角)并尝试设置以使其看起来像标签。如果您只想在其中显示静态文本。

答案 11 :(得分:2)

在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;

答案 12 :(得分: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

    }

答案 13 :(得分:2)

Swift 3

如果您想要带有背景颜色的圆形标签,除了大多数其他答案外,您还需要设置layer的背景色。设置view背景色时,它不起作用。

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

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

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

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

答案 14 :(得分:2)

  

使用Swift 3在Xcode 8.1.2中正常工作,在2017年8月进行了测试

“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
    }
}

<强>输出:

enter image description here

为什么选择扩展方法?

创建一个Swift文件并添加以下代码,其中包含Extention方法到“UILabel”类,其中此方法是用户定义的,但适用于应用程序中的所有标签,有助于保持一致性和清洁代码,如果您将来更改任何样式,只需要在扩展方法中。

答案 15 :(得分:0)

根据您的具体操作,您可以制作图像并以编程方式将其设置为背景。