在日常開(kāi)發(fā)中我們有時(shí)候會(huì)遇到View只有部分圓角的需求,這是我們可以讓UI給我們切符合需求的圖引镊,那么我們能不能用代碼實(shí)現(xiàn)這一需求呢,答案是肯定的。
上代碼
給view擴(kuò)展設(shè)置部分角是原角的方法
extension UIView {
/// 設(shè)置多個(gè)圓角
///
/// - Parameters:
/// - cornerRadii: 圓角幅度
/// - roundingCorners: UIRectCorner(rawValue: (UIRectCorner.topRight.rawValue) | (UIRectCorner.bottomRight.rawValue))
public func filletedCorner(_ cornerRadii:CGSize,_ roundingCorners:UIRectCorner) {
let fieldPath = UIBezierPath.init(roundedRect: bounds, byRoundingCorners: roundingCorners, cornerRadii:cornerRadii )
let fieldLayer = CAShapeLayer()
fieldLayer.frame =bounds
fieldLayer.path = fieldPath.cgPath
self.layer.mask = fieldLayer
}
}
調(diào)用
class TextViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let frame = CGRect(x: 0, y: 0, width: 150, height: 150)
let tempView = UIView(frame: frame)
tempView.backgroundColor = UIColor.o
tempView.center = self.view.center
view.addSubview(tempView)
tempView.ViewCornerRadius(CGSize(width: 5, height: 5),
UIRectCorner(rawValue: (UIRectCorner.topLeft.rawValue)|
(UIRectCorner.topRight.rawValue)))
}
}
在iOS11之前想要用代碼實(shí)現(xiàn)部分圓角在用以上方法虑椎,但是iOS11之后就沒(méi)必要這樣麻煩
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let frame = CGRect(x: 0, y: 0, width: 150, height: 150)
let tempView = UIView(frame: frame)
tempView.backgroundColor = UIColor.orange
tempView.center = view.center
view.addSubview(tempView)
if #available(iOS 11.0, *) {
// iOS11:只需要帶用這個(gè)系統(tǒng)方法就可以隨意設(shè)置View的圓角了,是不是很方便俱笛,趕快試一下吧
tempView.layer.cornerRadius = 10
tempView.layer.maskedCorners = CACornerMask(rawValue: CACornerMask.layerMinXMinYCorner.rawValue | CACornerMask.layerMaxXMinYCorner.rawValue)
} else {
tempView.ViewCornerRadius(CGSize(width: 5, height: 5), UIRectCorner(rawValue: (UIRectCorner.topLeft.rawValue)|(UIRectCorner.topRight.rawValue)))
}
}
}
運(yùn)行效果: