我正在Xcode 6的最新版本中使用swift构建一个应用程序,我想知道如何修改我的按钮,使它可以有一个圆形的边界,如果需要,我可以调整自己。一旦完成,我如何改变边界本身的颜色而不添加背景?换句话说,我想要一个略圆的按钮,没有背景,只有一个特定颜色的1pt边界。


当前回答

我认为这是简单的形式

Button1.layer.cornerRadius = 10(Half of the length and width)
Button1.layer.borderWidth = 2

其他回答

import UIKit

@IBDesignable
class RoundedButton: UIButton {
    
    @IBInspectable var cornerRadius: CGFloat = 8
    @IBInspectable var borderColor: UIColor? = .lightGray
    
    override func draw(_ rect: CGRect) {
        layer.cornerRadius = cornerRadius
        layer.masksToBounds = true
        layer.borderWidth = 1
        layer.borderColor = borderColor?.cgColor
        
    }
    
    
}
@IBOutlet weak var button: UIButton!

...

我认为对于半径来说,这个参数足够了:

button.layer.cornerRadius = 5

UIBuilder爱好者的解决方案:

检查UIButton的“Attribution Inspector”窗口中的“Clip to Bounds”复选框。[见下图1] 点击“身份检查器”,并点击“+”符号输入一个新的密钥路径:层。角半径,数字,8(或16等…) [见下图2]

图1:剪辑到边界复选框

图2:关键路径代码…

图3:结果图像按钮

要在故事板中完成这项工作(接口构建器检查器)

在IBDesignable的帮助下,我们可以为UIButton添加更多的界面构建器检查器选项,并在故事板上调整它们。首先,将以下代码添加到项目中。

@IBDesignable extension UIButton {

    @IBInspectable var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat {
        set {
            layer.cornerRadius = newValue
        }
        get {
            return layer.cornerRadius
        }
    }

    @IBInspectable var borderColor: UIColor? {
        set {
            guard let uiColor = newValue else { return }
            layer.borderColor = uiColor.cgColor
        }
        get {
            guard let color = layer.borderColor else { return nil }
            return UIColor(cgColor: color)
        }
    }
}

然后简单地设置storyboard上按钮的属性。

使用button.layer。cornerRadius, button.layer.borderColor和button.layer.borderWidth。 注意borderColor需要CGColor,所以你可以说(Swift 3/4):

button.backgroundColor = .clear
button.layer.cornerRadius = 5
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.black.cgColor