Home > Mobile >  Swift: How to round one corner of a button in storyboards?
Swift: How to round one corner of a button in storyboards?

Time:07-01

I know how to round both sides of a UIButton with: myButton.layer.cornerRadius = 10, but I am not sure how to round just one side so it would look something like this: Red button is rounded on left side not on right

CodePudding user response:

I don't think you can do it in IB, the usual way to do it would be to either set properties or manually via the User Defined Runtime Attributes.

However, setting the a corner radius but only for certain corners requires setting the layer maskedCorners array with values ([.layerMinXMinYCorner, .layerMinXMaxYCorner]) and that is not supported in IB.

The other option would be to write a subclass of UIButton that sets those values in the init method (particularly the init(coder:)) and then change in IB to use that class for the view.

CodePudding user response:

Use this extension into your project

 extension UIButton {
        func roundCorners(corners: UIRectCorner, radius: Int = 8) {
            let maskPath1 = UIBezierPath(roundedRect: bounds,
                                         byRoundingCorners: corners,
                                         cornerRadii: CGSize(width: radius, height: radius))
            let maskLayer1 = CAShapeLayer()
            maskLayer1.frame = bounds
            maskLayer1.path = maskPath1.cgPath
            layer.mask = maskLayer1
        }
    }

to call roundCorners Method

myButton.roundCorners(corners: [.topLeft, .bottomLeft])

Reference

If you need to use extension for all view components Change extension UIButton to extension UIView

  • Related