首页 > 解决方案 > 右上角在 swift 4 中不起作用 byRoundingcorners

问题描述

我正在尝试使用以下代码为左上角和右上角的子视图制作圆角

 maskLayer.path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: [.topRight, .topLeft], cornerRadii: CGSize(width: 10, height: 10)).cgPath

也在 viewDidLayoutSubviews() 中尝试过,但只有左边框半径有效……右边框半径无效。

有人可以帮我吗

标签: iosswiftuiview

解决方案


你可能会错过配置一些东西,这里是maskedCorners左上角&&右roundCorners圆——和左下角&&右圆

class ViewController: UIViewController {

    let redBox = UIView(frame: CGRect(x: 100, y: 100, width: 128, height: 128))
    let blueBox = UIView(frame: CGRect(x: 100, y: 300, width: 128, height: 128))
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        redBox.backgroundColor = .red
        redBox.layer.cornerRadius = 25
        redBox.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        view.addSubview(redBox)

        blueBox.backgroundColor = .blue
        view.addSubview(blueBox)
    }


    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        blueBox.roundCorners(corners: [.bottomLeft, .bottomRight], radius: 25.0)
    }

}

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

在此处输入图像描述


推荐阅读