简体   繁体   中英

How to round corners top left + top right corners for iOS 9

I'm trying to round the top and left corners but know how to do it for iOS 11+ (cause of the easiest new feature) but can't do that for iOS 9-, could be cool if u guys could help me with that:)

Here's an image of how it looks like now without rounding -

在此处输入图像描述 for example for iOS 11+, I do it like this -

layer.maskedCorners = [
  .layerMinXMaxYCorner,
  .layerMaxXMaxYCorner
]
layer.cornerCurve = .continuous

Write this method and put it wherever you need, for example in viewDidLoad:

private let cornerRadius: CGFloat = 10
private func setMaskLayers() {
        if #available(iOS 11.0, *) {
        yourView.clipsToBounds = true
        yourView.layer.cornerRadius = cornerRadius
        yourView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
    } else {
    let path = UIBezierPath(roundedRect: yourView.bounds, byRoundingCorners: [.topRight, .topLeft], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
    let maskLayer = CAShapeLayer()
    maskLayer.path = path.cgPath
    yourView.layer.mask = maskLayer
    } 
}

Make a UIView extension and add the below method in it:

extension UIView {
    
    func roundCorners(corners: UIRectCorner, radius: CGFloat) {
        DispatchQueue.main.async {
            let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let mask = CAShapeLayer()
            mask.frame = self.bounds
            mask.path = path.cgPath
            self.layer.mask = mask
        }
    }
}

And then you can round corner radius of any views from any sides. Example:

anyView.roundCorners(corners: [.topRight, .bottomLeft, .bottomRight], radius: 20)

Note: Don't forget to set the clipsToBounds property of the view to true before using this method. Happy Coding:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM