简体   繁体   中英

How to make sub view to be round corner as super view in iOS?

I have set a view (light gray) to be round corner using:

layer.masksToBounds = false
layer.cornerRadius = 10

It works fine. But when a sub view (dark gray) was added, that subview is not round as its super view. 圆角视图 How to make sub view to be round corner as super view?

在添加子视图时,请将masksToBounds设置为true

subView.masksToBounds = true

Try to add the cornerRadius to subview as well.

subview.layer.masksToBounds = false
subview.layer.cornerRadius = 10

Update

By using UIBezierPath we can add roundness to any corner we want.

subview.roundCorners([.topLeft, .topRight, .bottomRight], radius: 6)

Extension

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

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