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


当前回答

你可以使用UIButton的子类来根据你的需要定制UIButton。

访问这个github回购参考

class RoundedRectButton: UIButton {

    var selectedState: Bool = false

    override func awakeFromNib() {
        super.awakeFromNib()
        layer.borderWidth = 2 / UIScreen.main.nativeScale
        layer.borderColor = UIColor.white.cgColor
        contentEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    }


    override func layoutSubviews(){
        super.layoutSubviews()
        layer.cornerRadius = frame.height / 2
        backgroundColor = selectedState ? UIColor.white : UIColor.clear
        self.titleLabel?.textColor = selectedState ? UIColor.green : UIColor.white
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        selectedState = !selectedState
        self.layoutSubviews()
    }
}

其他回答

我认为这是简单的形式

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

基于@returntrue答案,我设法在接口生成器中实现它。

为了得到圆角按钮,使用界面生成器添加一个Key Path = "图层。按钮的标识检查器的“用户定义运行时属性”中的“Type =“Number”,Value =“10”(或其他需要的值)的“cornerRadius”。

它是UIButton圆角边框的全局方法

class func setRoundedBorderButton(btn:UIButton)
{
   btn.layer.cornerRadius = btn.frame.size.height/2
   btn.layer.borderWidth = 0.5
   btn.layer.borderColor = UIColor.darkGray.cgColor
}

使用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

我已经创建了一个简单的UIButton子模块,它使用tintColor作为文本和边框颜色,当高亮显示时,它的背景改变为tintColor。

class BorderedButton: UIButton {

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    layer.borderWidth = 1.0
    layer.borderColor = tintColor.CGColor
    layer.cornerRadius = 5.0
    clipsToBounds = true
    contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
    setTitleColor(tintColor, forState: .Normal)
    setTitleColor(UIColor.whiteColor(), forState: .Highlighted)
    setBackgroundImage(UIImage(color: tintColor), forState: .Highlighted)
}
}

这利用了一个UIImage扩展,从一个颜色创建一个图像,我发现代码在这里:https://stackoverflow.com/a/33675160

当在界面构建器中设置为自定义类型时,它工作得最好,因为默认的系统类型会在按钮突出显示时略微修改颜色。