【问题标题】:How do I create a round cornered UILabel on the iPhone?如何在 iPhone 上创建圆角 UILabel?
【发布时间】:2010-10-05 08:29:16
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    iOS 3.0 及更高版本

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

    view.layer.cornerRadius = 8;
    

    您需要#import <QuartzCore/QuartzCore.h> 并链接到 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 放置在视图上。在编译和运行应用程序之前,您不会看到矩形,但至少您可以放置​​子视图并将其连接到插座或操作(如果需要)。

    【讨论】:

    • view.layer.cornerRadius 仍然会绘制整个视图(启用时会在屏幕外),并且只有在 CoreAnimation 层才会剪辑您的视图。代价是它会使启用它的任何视图放在 UIScrollView 中,从而降低滚动性能。
    • 在 UIScrollView 中使用cornerRadius 会杀死您的滚动性能吗?如果我们谈论的是 UITableView,我可能相信你,但是单个圆角视图不会使视图绘制系统陷入停顿。
    • 如果您想在 Interface Builder 而不是代码中执行此操作,您可以在 Identity Inspector 中使用键路径“layer.cornerRadius”设置用户定义的运行时属性。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:
          1. 您有一个UILabel,称为:myLabel
          2. 在“m”或“h”文件导入中:#import <QuartzCore/QuartzCore.h>
          3. 在您的viewDidLoad 中写下这一行:self.myLabel.layer.cornerRadius = 8;

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

          祝你好运

          【讨论】:

            【解决方案6】:

            您可以通过这种方式制作具有任何控件边框宽度的圆角边框:-

            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>

            【讨论】:

              【解决方案7】:

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

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

              【讨论】:

              • 设置圆角半径,但 maskToBounds 对于滚动/动画来说很慢。如果您在 7.1 上将图层的背景颜色与视图结合起来就足够了(在 7.1 上它会停止使用cornerRadius)。
              【解决方案8】:
                  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
                  label.text = @"Your String.";
                  label.layer.cornerRadius = 8.0;
                  [self.view addSubview:label];
              

              【讨论】:

                【解决方案9】:

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

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

                【讨论】:

                • 请不要在将 Objective-C 答案翻译成 Swift 时弄乱 Stack Overflow,尤其是当这种情况下唯一的变化是将 YES 更改为 true 时。
                • 这种情况下的变化很小,但总的来说,从 Objective-C 到 Swift 的翻译通常非常有用。
                • 如何编辑原始答案并在那里添加 Swift 翻译?
                【解决方案10】:

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

                【讨论】:

                  【解决方案11】:

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

                  结果

                  使用过的 SO-帖子:

                  游乐场

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

                  【讨论】:

                    【解决方案12】:

                    在 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】:

                      xCode 7.3.1 iOS 9.3.2

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

                      【讨论】:

                        【解决方案14】:

                        斯威夫特 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,否则文本将左对齐。

                        【讨论】:

                          【解决方案15】:

                          如果您希望通过情节提要将 UI 对象(如(UILabelUIViewUIButtonUIImageView)设置为圆角,则将 clip to bounds 设置为 true 并将 User Defined Runtime Attributes 键路径设置为 layer.cornerRadius,type = Number 和 value = 9(根据您的要求)

                          【讨论】:

                            【解决方案16】:

                            在带有 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
                                }
                            }
                            

                            输出:

                            为什么要扩展方法?

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

                            【讨论】:

                              猜你喜欢
                              • 2012-04-10
                              • 2019-11-14
                              • 2021-11-17
                              • 1970-01-01
                              • 2018-04-03
                              • 1970-01-01
                              • 2020-10-27
                              • 2019-10-02
                              • 1970-01-01
                              相关资源
                              最近更新 更多