Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 如何仅使UILabel的顶部两个角变圆?_Iphone_Objective C_Ios_Uilabel - Fatal编程技术网

Iphone 如何仅使UILabel的顶部两个角变圆?

Iphone 如何仅使UILabel的顶部两个角变圆?,iphone,objective-c,ios,uilabel,Iphone,Objective C,Ios,Uilabel,我知道在iOS 3.0+中我可以使用 label.layer.cornerRadius = xxx; 要使UILabel(作为UIView子类)的所有四个角都成圆角,但我只希望使标签的顶部两个角成圆角,并使底部角保持直角 我有没有办法用UILabel来做这件事?其他解决方案采用自定义UIView,而不是UILabel。我已经检查了UIView&UILabel及其层的类引用,但找不到任何方法使用iOS提供的方法来实现这一点 您可以做一件事,创建一个UIView&对其应用圆角。现在添加一个ui标

我知道在iOS 3.0+中我可以使用

 label.layer.cornerRadius = xxx;
要使UILabel(作为UIView子类)的所有四个角都成圆角,但我只希望使标签的顶部两个角成圆角,并使底部角保持直角


我有没有办法用UILabel来做这件事?其他解决方案采用自定义UIView,而不是UILabel。

我已经检查了UIView&UILabel及其层的类引用,但找不到任何方法使用iOS提供的方法来实现这一点


您可以做一件事,创建一个
UIView
&对其应用圆角。现在添加一个
ui标签
作为此ui视图的子视图,并将其放置在标签覆盖底部2个圆角的位置。通过这种方式,您可以获得所需的效果…

您可以使用Calayer和面具来实现这一点

CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = maskPath.CGPath;
label.layer.mask = maskLayer;

其中,maskPath是一个UIBezierPath,使用
bezierPathWithRoundedRect:byRoundingCorners:cornerRadii设置。我想我会发布包含BezierPath的完整代码

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

CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = bounds;
maskLayer.path = maskPath.CGPath;

label.layer.mask = maskLayer;
对于Swift 4.0:

let bounds: CGRect = label.bounds
let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: ([.topLeft, .topRight]), cornerRadii: CGSize(width: 5.0, height: 5.0))
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = maskPath.cgPath
label.layer.mask = maskLayer

并确保UIView和UILabel具有相同的颜色。我认为应该是label.layer.mask=masklayer接受这个答案,因为我不想在这里使用额外的视图。我使用两个覆盖层,底层全部圆角,顶层仅顶部两个角圆角。使之生效