Кнопка прозрачного фона с двухсторонним радиусом угла в Swift - PullRequest
0 голосов
/ 09 июля 2020

Я создаю свой собственный segmentedControl. Это полый (прозрачный) segmentedControl. Граница выделенного сегмента будет подчеркнута. Каждый сегмент представляет собой кнопку в горизонтальной стопке. Вот чего я хочу добиться:

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:

введите описание изображения здесь

Все равно закруглить углы только слева без маскировки?

1 Ответ

1 голос
/ 09 июля 2020

Вы можете отредактировать roundCorners функцию, как показано ниже;

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)
    }
}

и использовать ее как:

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)

введите описание изображения здесь

...