如何在 iPhone 上创建圆角 UILabel?

发布于 2024-07-12 23:27:41 字数 54 浏览 8 评论 0原文

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

Is there a built in way to create round-cornered UILabels? If the answer is no, how would one go about creating such an object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

飘逸的'云 2024-07-19 23:27:42

我创建了一个 swift UILabel 子类来实现此效果。 此外,我自动将文本颜色设置为黑色或白色以获得最大对比度。

结果

colors- rounded-borders

使用过的 SO-Posts:

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())

I made a swift UILabel subclass to achieve this effect. In addition I automatically set the text color to either black or white for maximal contrast.

Result

colors-rounded-borders

Used SO-Posts:

Playground

Just paste this into an 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())
成熟的代价 2024-07-19 23:27:42

如果你想要 UI 对象的圆角,例如(UILabelUIViewUIButtonUIImageView),请通过 Storyboard 设置clip to borders true 并将用户定义的运行时属性键路径设置为
layer.cornerRadius,类型=数字和值= 9(根据您的要求)

将剪辑设置为边界
设置用户定义运行时属性为

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

嗼ふ静 2024-07-19 23:27:42

xCode 7.3.1 iOS 9.3.2

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

xCode 7.3.1 iOS 9.3.2

 _siteLabel.layer.masksToBounds = true;
  _siteLabel.layer.cornerRadius = 8;
深海里的那抹蓝 2024-07-19 23:27:42

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

Another method is to place a png behind the UILabel. I have views with several labels that overlay a single background png that has all the artwork for the individual labels.

回忆凄美了谁 2024-07-19 23:27:42

在 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”类的扩展方法,其中此方法是用户定义的,但适用于应用程序中的所有标签,并且如果您将来更改任何样式,只需在扩展方法中更改,将有助于保持一致性和干净的代码。

Works fine in Xcode 8.1.2 with Swift 3

.cornerRadius is the key property to set rounded edges. If you are using the same style for all labels in your application, I would recommend for an extension method.

Code:

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

Output:

enter image description here

Why Extension method?

Create a Swift file and add the following code, which has the Extention method to the "UILabel" class, where this method is user defined but will work for all the label in your application and will help to maintain consistency and clean code, if you change any style in future require only in the extension method.

烟织青萝梦 2024-07-19 23:27:42
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    label.text = @"Your String.";
    label.layer.cornerRadius = 8.0;
    [self.view addSubview:label];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    label.text = @"Your String.";
    label.layer.cornerRadius = 8.0;
    [self.view addSubview:label];
等往事风中吹 2024-07-19 23:27:42

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

In Monotouch / Xamarin.iOS I solved the same problem like this:

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;
海螺姑娘 2024-07-19 23:27:42

在 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

    }

Works perfect in 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

    }
时光病人 2024-07-19 23:27:42

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

Did you try using the UIButton from the Interface builder (that has rounded corners) and experimenting with the settings to make it look like a label. if all you want is to display static text within.

魂归处 2024-07-19 23:27:42

根据您正在做什么,您可以制作图像并以编程方式将其设置为背景。

Depending on what exactly you are doing you could make an image and set it as the background programatically.

终弃我 2024-07-19 23:27:41

iOS 3.0 及更高版本

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

view.layer.cornerRadius = 8;

您将需要 #import 并链接到 QuartzCore 框架才能访问 CALayer 的标头和属性。

在 iOS 3.0 之前

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

  1. 创建一个 UIView 子类并将其命名为 RoundRectView 之类的名称。
  2. RoundRectViewdrawRect: 方法中,使用 Core Graphics 调用(例如用于边缘的 CGContextAddLineToPoint() 和用于圆角的 CGContextAddArcToPoint())在视图边界周围绘制一条路径角落。
  3. 创建一个 UILabel 实例并使其成为 RoundRectView 的子视图。
  4. 将标签的框架设置为 RoundRectView 边界内嵌的几个像素。 (例如,label.frame = CGRectInset(roundRectView.bounds, 8, 8);

如果您创建通用 UIView,然后使用以下命令更改其类,则可以使用 Interface Builder 将 RoundRectView 放置在视图上检查员。 在编译并运行应用程序之前,您不会看到该矩形,但至少您可以放置​​子视图并将其连接到插座或操作(如果需要)。

iOS 3.0 and later

iPhone OS 3.0 and later supports the cornerRadius property on the CALayer class. Every view has a CALayer instance that you can manipulate. This means you can get rounded corners in one line:

view.layer.cornerRadius = 8;

You will need to #import <QuartzCore/QuartzCore.h> and link to the QuartzCore framework to get access to CALayer's headers and properties.

Before iOS 3.0

One way to do it, which I used recently, is to create a UIView subclass which simply draws a rounded rectangle, and then make the UILabel or, in my case, UITextView, a subview inside of it. Specifically:

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

You can place the RoundRectView on a view using Interface Builder if you create a generic UIView and then change its class using the inspector. You won't see the rectangle until you compile and run your app, but at least you'll be able to place the subview and connect it to outlets or actions if needed.

丿*梦醉红颜 2024-07-19 23:27:41

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

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

For devices with iOS 7.1 or later, you need to add:

yourUILabel.layer.masksToBounds = YES;
yourUILabel.layer.cornerRadius = 8.0;
何以心动 2024-07-19 23:27:41

对于基于 OScarsWyck 答案的 Swift IOS8 及以上版本:

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

For Swift IOS8 onwards based on OScarsWyck answer:

yourUILabel.layer.masksToBounds = true
yourUILabel.layer.cornerRadius = 8.0
相思碎 2024-07-19 23:27:41
  1. 您有一个名为:myLabelUILabel
  2. 在您的“m”或“h”文件导入中:#import
  3. 在您的viewDidLoad中写入以下行:self .myLabel.layer.cornerRadius = 8;

    • 取决于您想要如何将cornerRadius值从8更改为其他数字:)

祝你好运

  1. you have an UILabel called: myLabel.
  2. in your "m" or "h" file import: #import <QuartzCore/QuartzCore.h>
  3. in your viewDidLoad write this line: self.myLabel.layer.cornerRadius = 8;

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

Good luck

相思故 2024-07-19 23:27:41

您可以通过以下方式使任何控件的边框宽度为圆形边框:-

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 即可。

注意:-不要忘记导入

You can make rounded border with width of border of any control in this way:-

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>

兮子 2024-07-19 23:27:41

Swift 3

如果您想要带有背景颜色的圆形标签,除了大多数其他答案之外,您还需要设置图层的背景颜色。 设置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,否则文本将左对齐。

Swift 3

If you want rounded label with background color, in addition to most of the other answers, you need to set layer's background color as well. It does not work when setting view background color.

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

If you are using auto layout, want some padding around the label and do not want to set the size of the label manually, you can create UILabel subclass and override intrinsincContentSize property:

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

To combine the two you will also need to set label.textAlignment = center, otherwise the text would be left aligned.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文