I am applying corner radius to only top left and top right of a view. In viewDidLoad()
I have:
if #available(iOS 11.0, *) {
view.layer.cornerRadius = 20.0
view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
}
If iOS 11 is not available, the best way seems to do it in draw(_ rect:)
. Since I have to override it outside viewDidLoad()
, I want to do the following
if NOT #available(iOS 11.0, *) {
override func draw(_ rect: CGRect) {
let maskPath = UIBezierPath(roundedRect: self.contentView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 20.0, height: 20.0))
let shapeLayer = CAShapeLayer()
shapeLayer.frame = self.bounds
shapeLayer.path = maskPath.cgPath
view.layer.mask = shapeLayer
}
}
It is syntactically incorrect of course. What should I do?
if you need to support earlier versions than iOS 11 then use #available
inside the function draw(rect:)
and use else part to apply logic on earlier versions
override func draw(_ rect: CGRect) {
if #available(iOS 11, *) {} else {
let maskPath = UIBezierPath(roundedRect: self.contentView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 20.0, height: 20.0))
let shapeLayer = CAShapeLayer()
shapeLayer.frame = self.bounds
shapeLayer.path = maskPath.cgPath
view.layer.mask = shapeLayer
}
}
Swift 5.6 and above: use #unavailable
override func draw(_ rect: CGRect) {
if #unavailable(iOS 11, *) {
let maskPath = UIBezierPath(roundedRect: self.contentView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 20.0, height: 20.0))
let shapeLayer = CAShapeLayer()
shapeLayer.frame = self.bounds
shapeLayer.path = maskPath.cgPath
view.layer.mask = shapeLayer
}
}