21

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?

Jack Guo
  • 3,959
  • 8
  • 39
  • 60
  • 2
    You can use `else` part to fall back to older version `if #available(iOS 11.0, *) { view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMaxYCorner] } else { // Fallback on earlier versions }` – Subramanian P Feb 28 '18 at 03:12
  • I cannot override `draw(_ rect:)` in `viewDidLoad()` – Jack Guo Feb 28 '18 at 03:28

1 Answers1

49

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
    }
 }

update Swift 5.6: 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
   }     
}
Suhit Patil
  • 11,748
  • 3
  • 50
  • 60