设置圆角半径隐藏 UIView
Setting corner radius hides UIView
我创建了这个扩展来快速添加圆角到任何 UIView
:
extension UIView {
func setCorners(corners: UIRectCorner, radius: CGFloat) {
print(self.frame) //-> (359.0, 0.0, 306.0, 37.0)
let maskPath = UIBezierPath(roundedRect: self.frame, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: 0.0))
let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.cgPath
self.layer.mask = maskLayer
print(self.frame) //-> (359.0, 0.0, 306.0, 37.0)
}
}
我用来创建视图和圆角的代码:
let view = UIView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 100, height: 40))) //I reposition the view later
view.setCorners(corners: [.bottomLeft, .bottomRight], radius: 8)
注释掉 setCorners(corners:radius:)
时,视图出现,否则保持隐藏状态。
知道为什么会这样吗?
您屏蔽了错误的视图区域,试试这个:
let maskPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height), byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: 0.0))
看来,您需要在 UIBezierPath(roundedRect: self.frame, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: 0.0))
中使用 self.bounds 而不是 self.frame
我创建了这个扩展来快速添加圆角到任何 UIView
:
extension UIView {
func setCorners(corners: UIRectCorner, radius: CGFloat) {
print(self.frame) //-> (359.0, 0.0, 306.0, 37.0)
let maskPath = UIBezierPath(roundedRect: self.frame, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: 0.0))
let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.cgPath
self.layer.mask = maskLayer
print(self.frame) //-> (359.0, 0.0, 306.0, 37.0)
}
}
我用来创建视图和圆角的代码:
let view = UIView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 100, height: 40))) //I reposition the view later
view.setCorners(corners: [.bottomLeft, .bottomRight], radius: 8)
注释掉 setCorners(corners:radius:)
时,视图出现,否则保持隐藏状态。
知道为什么会这样吗?
您屏蔽了错误的视图区域,试试这个:
let maskPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height), byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: 0.0))
看来,您需要在 UIBezierPath(roundedRect: self.frame, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: 0.0))