简体   繁体   中英

Rounded corner on UIView not working only in few simulators like iPhone8, iPhone6s, iPhone6s plus, iPhone 6

I have a requirement to get rounded corner on the top left and right of a view. Below is the code for the same.

let size = CGSize(width: 30, height: 30)
        let bezierPath = UIBezierPath(roundedRect: self.alertView.bounds, byRoundingCorners: [.topRight, .topLeft], cornerRadii: size)
        let shapeLayer = CAShapeLayer()
        shapeLayer.frame = self.alertView.bounds
        shapeLayer.path = bezierPath.cgPath
        self.alertView.layer.mask = shapeLayer

This is working fine in all the simulators iPhone 8 plus and above. But for the rest of the simulators like iPhone 6, iPhone 6 plus etc the code is not working as required. I even tried using multiple types of views but it is not working as per the requirement. I get only rounded corner on the left side but not on the right. Below are the screenshots of the UIView from different simulators

iPhone 11 (working fine)

在此处输入图像描述

iPhone 8 (not working as per requirement)

在此处输入图像描述

I am not getting the issue here. Kindly help!

Why don't you simply use maskedCorners and cornerRadius for that?

self.alertView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
self.alertView.layer.cornerRadius = 10.0

Screenshot:

在此处输入图像描述

Add corner Radius in viewDidLayoutSubviews() instead of viewDidLoad()

 override func viewDidLayoutSubviews() {
     self.alertView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
     self.alertView.layer.cornerRadius = 10.0
}

Try

let size = CGSize(width: view.frame.size.width * 0.80, height: 30)

or

let size = CGSize(width: UIScreen.main.bounds.width * 0.065, height: 30)

Numbers can change. It means that the width is up to 80 percent of the phone's screen.

I have tested this on every device. please try this one:

  let viewSub = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 200, height: 200))

viewSub.backgroundColor = .red
viewSub.center =  self.view.center
self.view.addSubview(viewSub)

let rectShape = CAShapeLayer()
rectShape.bounds = viewSub.frame
rectShape.position = viewSub.center
rectShape.path = UIBezierPath(roundedRect: viewSub.bounds, byRoundingCorners: [ .topRight , .topLeft], cornerRadii: CGSize(width: 20, height: 20)).cgPath

viewSub.layer.backgroundColor = UIColor.red.cgColor
//Here I'm masking the textView's layer with rectShape layer
viewSub.layer.mask = rectShape

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