ios 如何在 iPhone 上创建圆角 UILabel?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/510382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:37:00  来源:igfitidea点击:

How do I create a round cornered UILabel on the iPhone?

iosobjective-ccocoa-touchuilabelrounded-corners

提问by newtonapple

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?

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

回答by benzado

iOS 3.0 and later

iOS 3.0 及更高版本

iPhone OS 3.0 and later supports the cornerRadiusproperty on the CALayerclass. Every view has a CALayerinstance that you can manipulate. This means you can get rounded corners in one line:

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

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.

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

Before iOS 3.0

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:

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

  1. Create a UIViewsubclass 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 UILabelinstance 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);)
  1. 创建一个UIView子类并将其命名为RoundRectView.
  2. RoundRectViewdrawRect:方法中,使用 Core Graphics 调用(如用于边缘的 CGContextAddLineToPoint() 和用于圆角的 CGContextAddArcToPoint() 等核心图形调用绘制围绕视图边界的路径。
  3. 创建一个UILabel实例并使其成为 RoundRectView 的子视图。
  4. 将标签的框架设置为 RoundRectView 边界的几个像素内嵌。(例如,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.

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

回答by OscarWyck

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

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

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

回答by VBaarathi

For Swift IOS8 onwards based on OScarsWyck answer:

对于基于 OScarsWyck 的 Swift IOS8 以后的回答:

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

回答by Gabriel

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

    • depends on how you want you can change cornerRadius value from 8 to other number :)
  1. 你有一个UILabel电话:myLabel
  2. 在您的“m”或“h”文件导入中: #import <QuartzCore/QuartzCore.h>
  3. 在你viewDidLoad写这一行:self.myLabel.layer.cornerRadius = 8;

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

Good luck

祝你好运

回答by Piyush Dubey

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 lblNamewith your UILabel.

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


只需替换lblName为您的UILabel.

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

回答by Alpinista

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.

另一种方法是在 UILabel 后面放置一个 png。我有多个标签的视图,这些标签覆盖了一个背景 png,该背景 png 具有各个标签的所有图稿。

回答by Besi

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

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

Result

结果

colors-rounded-borders

颜色圆形边框

Used SO-Posts:

使用的 SO-Posts:

Playground

操场

Just paste this into an iOS 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())

回答by Ahmed Abdallah

xCode 7.3.1 iOS 9.3.2

xCode 7.3.1 iOS 9.3.2

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

回答by Nikhlesh Bagdiya

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

如果您希望故事板的 UI 对象(如 ( UILabel, UIView, UIButton, UIImageView)圆角,则设置clip to boundstrue 并将User Defined Runtime AttributesKey path设置为 layer.cornerRadius, type = Number 和 value = 9 (根据您的要求)

Set clip to bounds asSet User Defined Runtime Attributes as

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

回答by Gaurav Gilani

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