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


当前回答

基于@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
}

UIBuilder爱好者的解决方案:

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

图1:剪辑到边界复选框

图2:关键路径代码…

图3:结果图像按钮

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

试试这个 带有圆角的按钮边框

anyButton.backgroundColor = .clear

anyButton.layer.cornerRadius = anyButton.frame.height / 2

anyButton.layer.borderWidth = 1

anyButton.layer.borderColor = UIColor.black.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