Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift how to check if API is NOT available [duplicate]

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?

like image 565
Jack Guo Avatar asked Feb 28 '18 03:02

Jack Guo


1 Answers

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
        }
     }
like image 72
Suhit Patil Avatar answered Oct 06 '22 20:10

Suhit Patil