嗨,我正在寻找一个干净的解决方案,不覆盖drawRect或类似的东西,以创建一个UIView与圆角上的View.我这里的主要问题是,如果视图正在调整大小或类似的事情,则创建变量解决方案.

推荐答案

可以通过在视图的图层上设置mask来实现:

CAShapeLayer * maskLayer = [CAShapeLayer layer];
maskLayer.path = [UIBezierPath bezierPathWithRoundedRect: self.bounds byRoundingCorners: UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii: (CGSize){10.0, 10.}].CGPath;

self.layer.mask = maskLayer;

IMPORTANT:您应该在视图的layoutSubviews()方法中执行此操作,因此视图已经从情节提要中调整了大小


In Swift <= 1.2

let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: .TopLeft | .TopRight, cornerRadii: CGSize(width: 10.0, height: 10.0)).CGPath

layer.mask = maskLayer

Swift 2.x

let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: UIRectCorner.TopLeft.union(.TopRight), cornerRadii: CGSizeMake(10, 10)).CGPath
layer.mask = maskLayer

Swift 3.x

let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 10, height: 10)).cgPath
layer.mask = maskLayer

Objective-c相关问答推荐

react 本机WebView菜单项目props 无法在iOS&>=16上使用

CLLocationManager startUpdatingLocation 未调用 locationManager:didUpdateLocations: 或 locationManager:didFailWithError:

从日、月、年生成 NSDate

将 CFDictionaryRef 转换为 NSDictionary?

在 ARC 中清零弱引用

setStatusBarHidden 在 iOS 9.0 中已弃用

如何在另一个视图中获取视图的框架?

当单元格全屏时,为什么 UICollectionView 会记录错误?

类在两者中都实现.将使用两者之一

将 NSData 字节转换为 NSString?

WKWebView 判断 JavaScript 返回值

Objective-C 中的 super 到底是什么?

Objective-C 中的非正式协议?

为什么 LLDB 不能打印 view.bounds?

100% 不透明度 UILabel 超过 50% 不透明度背景(UIView?)

如何更改标签栏上的非活动图标/文本 colored颜色 ?

请求访问相机胶卷的权限

如何实现全局 iPhone 异常处理?

使用 cocoaLumberjack 将日志(log)文件存储在哪里

无法在 iOS7 上将 UITextField 添加到 UIAlertView ...在 iOS 6 中有效