【问题标题】:Set rounded corners for UILabel为 UILabel 设置圆角
【发布时间】:2018-09-04 10:36:30
【问题描述】:

有没有办法为 UILabel 的右上角和右下角设置cornerRadius?

我尝试了以下方法,但它根本不起作用,使用下面的代码我没有得到预期的输出。所以如果需要,任何人都可以在我的代码中进行更正吗?

 UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:lblCollectPaymentAmount.bounds
                                               byRoundingCorners:(UIRectCornerTopRight | UIRectCornerBottomRight)
                                                     cornerRadii:CGSizeMake(5.0, 5.0)];

CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = lblCollectPaymentAmount.bounds;
maskLayer.path = maskPath.CGPath;
lblCollectPaymentAmount.layer.mask = maskLayer;
lblCollectPaymentAmount.layer.masksToBounds = YES;

【问题讨论】:

  • 您的代码运行良好。你检查你的标签背景颜色了吗

标签: ios objective-c uilabel uibezierpath rounded-corners


【解决方案1】:

@drashti:

它可能会帮助你:

    let rectShape = CAShapeLayer()
    rectShape.bounds = self.customView.frame
    rectShape.position = self.customView.center
    rectShape.path = UIBezierPath(roundedRect: self.customView.bounds, byRoundingCorners: [.bottomLeft , .bottomRight , .topLeft], cornerRadii: CGSize(width: 20, height: 20)).cgPath

    self.customView.layer.backgroundColor = UIColor.green.cgColor
    //Here I'm masking the textView's layer with rectShape layer
    self.customView.layer.mask = rectShape

【讨论】:

  • 在我的情况下 customview 应该是我的标签对吧?但虽然它不起作用。
  • @drashti : 是的,这里 customView 是标签
  • 正如@vp2698 所建议的,请给它一个背景颜色来检查。
【解决方案2】:

在IOS 11中出现maskedCorners属性。

【讨论】:

    【解决方案3】:

    Apple 在 iOS 11 及更高版本中引入了maskedCorners 属性,非常方便。

        lbl.clipsToBounds = true
        lbl.layer.cornerRadius = 10
        lbl.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        //You can give an array for .layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner and .layerMaxXMaxYCorner to give all corner a radius.
    

    您还可以为标签声明一个 IBDesignable 类。

    @IBDesignable
    class CornerLable: UILabel {
        @IBInspectable var cornerRadius:CGFloat = 10
    
        override func layoutSubviews() {
            layer.cornerRadius = cornerRadius
            layer.maskedCorners = [.layerMinXMinYCorner,.layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]
        }
    }
    

    不要忘记在故事板或代码中提供clipsToBounds = true

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      相关资源
      最近更新 更多