Eddy
Eddy

Reputation: 315

Transparent background button with 2 sided corner radius in Swift

I am building my own segmentedControl. It’s a hollow (transparent) segmentedControl. A selected segment has its borderWidth accentuated. Each segment is a button in a horizontal stack. This is what I want to achieve:

enter image description here

I am using this extension to round the selected button

extension UIButton {
    func roundedButton(corners: UIRectCorner, radius: CGFloat){
        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
    }
}

The output is the following:

enter image description here

Anyway to round the corners only on left without masking?

Upvotes: 0

Views: 317

Answers (1)

Omer Faruk Ozturk
Omer Faruk Ozturk

Reputation: 1852

You can edit roundCorners function like below;

extension UIButton {
    
    func roundCorners(_ corners: UIRectCorner, radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        layer.mask = mask
        
        let borderLayer = CAShapeLayer()
        borderLayer.path = path.cgPath
        borderLayer.lineWidth = borderWidth
        borderLayer.strokeColor = borderColor.cgColor
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.frame = bounds
        layer.addSublayer(borderLayer)
    }
}

and use it like:

let button = UIButton(frame: CGRect(x: 50, y: 50, width: 100, height: 40))
button.setTitle("Today", for: .normal)
button.roundCorners([.topLeft, .bottomLeft], radius: 25, borderColor: .white, borderWidth: 10)

enter image description here

Upvotes: 1

Related Questions