Home > Net >  can't make round corners for UIView
can't make round corners for UIView

Time:07-14

I have a UIView object inside a horizontal stackView. I'm calling this function inside LayoutSubviews:

     func roundCorners(corners: UIRectCorner, radius: CurveRadius) {
        var r = CGFloat()
        switch radius {
        case .small:
            r = self.frame.width / 30
        case .medium:
            r = self.frame.width / 25
        }
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: r, height: r))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        layer.mask = mask
    }

but it just doesn't work. I guess it has something to do with a stackView. can anyone help me out?

CodePudding user response:

extension UIView {
    /// Rounds ``UIView`` corners.
    /// - Parameters:
    ///   - maskedCorners: Corners to be rounded.
    ///   - cornerRadius: Value to be set as corner radius.
    func roundCorners(maskedCorners: CACornerMask,
                      cornerRadius: CGFloat) {
        layer.cornerRadius = cornerRadius
        layer.maskedCorners = maskedCorners
        layer.masksToBounds = true
    }
}

CodePudding user response:

I'm not sure if the UIStackView is the problem here, but there's another, more re-usable way to do this using a CACornerMask on the UIView's layer in an extension:

extension UIView {
    func roundCorners() {
        self.layer.cornerRadius = 10
        self.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner]
    }
}

When you create your view, just call the roundCorners(), like this:


private lazy var roundCorneredView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        view.backgroundColor = .red
        view.roundCorners()
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

Then add that view to your hierarchy in the usual way using addSubview.

CACornerMask docs @ Apple

  • Related