问题描述
有没有办法只为 UIView
的左上角和右上角设置 cornerRadius
?
Is there a way to set cornerRadius
for only top-left and top-right corner of a UIView
?
我尝试了以下方法,但最终还是看不到视图.
I tried the following, but it end up not seeing the view anymore.
UIView *view = [[UIView alloc] initWithFrame:frame];
CALayer *layer = [CALayer layer];
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRoundedRect:frame byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(3.0, 3.0)];
layer.shadowPath = shadowPath.CGPath;
view.layer.mask = layer;
推荐答案
请注意,如果您附加了布局约束,则必须在您的 UIView 子类中按如下方式刷新它:
Pay attention to the fact that if you have layout constraints attached to it, you must refresh this as follows in your UIView subclass:
override func layoutSubviews() {
super.layoutSubviews()
roundCorners(corners: [.topLeft, .topRight], radius: 3.0)
}
如果你不这样做,它就不会出现.
If you don't do that it won't show up.
要圆角,请使用扩展名:
And to round corners, use the extension:
extension UIView {
func roundCorners(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}
额外的视图控制器案例:无论你不能或不想子类化一个视图,你仍然可以围绕一个视图.通过覆盖 viewWillLayoutSubviews()
函数从其视图控制器执行此操作,如下所示:
Additional view controller case: Whether you can't or wouldn't want to subclass a view, you can still round a view. Do it from its view controller by overriding the viewWillLayoutSubviews()
function, as follows:
class MyVC: UIViewController {
/// The view to round the top-left and top-right hand corners
let theView: UIView = {
let v = UIView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))
v.backgroundColor = .red
return v
}()
override func loadView() {
super.loadView()
view.addSubview(theView)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// Call the roundCorners() func right there.
theView.roundCorners(corners: [.topLeft, .topRight], radius: 30)
}
}
这篇关于如何仅为 UIView 的左上角和右上角设置cornerRadius?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!