我正在Xcode 6的最新版本中使用swift构建一个应用程序,我想知道如何修改我的按钮,使它可以有一个圆形的边界,如果需要,我可以调整自己。一旦完成,我如何改变边界本身的颜色而不添加背景?换句话说,我想要一个略圆的按钮,没有背景,只有一个特定颜色的1pt边界。
当前回答
我认为最简单和最干净的方法是使用协议来避免继承和代码重复。 您可以直接从故事板更改此属性
protocol Traceable {
var cornerRadius: CGFloat { get set }
var borderColor: UIColor? { get set }
var borderWidth: CGFloat { get set }
}
extension UIView: Traceable {
@IBInspectable var cornerRadius: CGFloat {
get { return layer.cornerRadius }
set {
layer.masksToBounds = true
layer.cornerRadius = newValue
}
}
@IBInspectable var borderColor: UIColor? {
get {
guard let cgColor = layer.borderColor else { return nil }
return UIColor(cgColor: cgColor)
}
set { layer.borderColor = newValue?.cgColor }
}
@IBInspectable var borderWidth: CGFloat {
get { return layer.borderWidth }
set { layer.borderWidth = newValue }
}
}
更新
在这个链接中,您可以找到一个使用Traceable协议实用程序的示例
其他回答
它是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
}
试试这个 带有圆角的按钮边框
anyButton.backgroundColor = .clear
anyButton.layer.cornerRadius = anyButton.frame.height / 2
anyButton.layer.borderWidth = 1
anyButton.layer.borderColor = UIColor.black.cgColor
基于@returntrue答案,我设法在接口生成器中实现它。
为了得到圆角按钮,使用界面生成器添加一个Key Path = "图层。按钮的标识检查器的“用户定义运行时属性”中的“Type =“Number”,Value =“10”(或其他需要的值)的“cornerRadius”。
UIBuilder爱好者的解决方案:
检查UIButton的“Attribution Inspector”窗口中的“Clip to Bounds”复选框。[见下图1] 点击“身份检查器”,并点击“+”符号输入一个新的密钥路径:层。角半径,数字,8(或16等…) [见下图2]
图1:剪辑到边界复选框
图2:关键路径代码…
图3:结果图像按钮
使用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
推荐文章
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- Swift:理解// MARK
- Swift -转换为绝对值
- Swift编译器错误:“框架模块内的非模块化头”
- 从父iOS访问容器视图控制器
- 在代码中为UIButton设置一个图像
- NSRange从Swift Range?
- 我可以使用范围操作符与if语句在Swift?
- 在Swift中转换字符串为日期
- 点击按钮时如何打开手机设置?
- 在Swift中使用自定义消息抛出错误/异常的最简单方法?
- 编译器错误:带有Objective-C选择器的方法与前面带有相同Objective-C选择器的声明冲突
- 如何在Swift中获得唯一的设备ID ?
- 如何在Swift中获得枚举值的名称?
- 如何调用手势点击在UIView编程在迅速