在iPhone上如何创建圆角UILabel?

154

有没有内置的方法可以创建圆角UILabel? 如果答案是否定的,那么怎样才能创建这样一个对象呢?

16个回答

5

在使用 Swift 3 的 Xcode 8.1.2 中可以正常工作。

.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文件并添加以下代码,这里有一个将“UILabel”类扩展的方法,该方法是用户定义的,但将适用于应用程序中的所有标签,并且将有助于保持一致性和干净的代码,如果您在未来需要更改任何样式,则只需在扩展方法中进行修改。


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

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

    }

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;

2

您是否尝试过使用来自界面构建器的UIButton(带有圆角),并尝试使用设置使其看起来像标签。如果您只想显示静态文本,则可以这样做。


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接