编辑UIButton以在一侧具有圆角

时间:2017-05-15 18:52:31

标签: ios swift uibutton

我对Swift相当新,我试图了解如何编辑UIButtons以使它们看起来像某种方式。我想知道如何让我的UIButton看起来像:

this

2 个答案:

答案 0 :(得分:3)

试试这个:

extension UIView {
    func roundCorners(_ corners: UIRectCorner, radius: CGFloat, borderColor: UIColor?, borderWidth: CGFloat?) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))

        let mask = CAShapeLayer()
        mask.frame = self.bounds
        mask.path = path.cgPath
        self.layer.mask = mask

        if borderWidth != nil {
            addBorder(mask, borderWidth: borderWidth!, borderColor: borderColor!)
        }
    }

    private func addBorder(_ mask: CAShapeLayer, borderWidth: CGFloat, borderColor: UIColor) {
        let borderLayer = CAShapeLayer()
        borderLayer.path = mask.path
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.strokeColor = borderColor.cgColor
        borderLayer.lineWidth = borderWidth
        borderLayer.frame = bounds
        layer.addSublayer(borderLayer)
    }
}

用法:

someView.roundCorners([.topLeft, .topRight], radius: 3, borderColor: nil, borderWidth: nil) //top corners with radius 3 without border
someView.roundCorners(.allCorners, radius: 2, borderColor: UIColor.red, borderWidth: 1) //all corners with red border

你可以将它应用于任何继承UIView的UI元素(例如UIButton)

答案 1 :(得分:0)

在这种情况下,我会制作一个带有白色文字的透明按钮。

然后我会定义边框的颜色和大小:

self.myButton.layer.layer.borderColor  = UIColor.white
self.myButton.layer.layer.borderWidth  = 3

接下来我会按下按钮:

self.myButton.layer.cornerRadius = 3
self.myButton.clipsToBounds = true

要使背景变为红色,只需将按钮放在此颜色的视图顶部

即可