我正在Xcode 6的最新版本中使用swift构建一个应用程序,我想知道如何修改我的按钮,使它可以有一个圆形的边界,如果需要,我可以调整自己。一旦完成,我如何改变边界本身的颜色而不添加背景?换句话说,我想要一个略圆的按钮,没有背景,只有一个特定颜色的1pt边界。
当前回答
基于@returntrue答案,我设法在接口生成器中实现它。
为了得到圆角按钮,使用界面生成器添加一个Key Path = "图层。按钮的标识检查器的“用户定义运行时属性”中的“Type =“Number”,Value =“10”(或其他需要的值)的“cornerRadius”。
其他回答
我认为最简单和最干净的方法是使用协议来避免继承和代码重复。 您可以直接从故事板更改此属性
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协议实用程序的示例
要在故事板中完成这项工作(接口构建器检查器)
在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
它是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
}
我认为这是简单的形式
Button1.layer.cornerRadius = 10(Half of the length and width)
Button1.layer.borderWidth = 2
推荐文章
- 为什么Swift的编译时间这么慢?
- 如何测试等价的Swift枚举与相关的值
- 如何创建一个Swift Date对象?
- 在Swift中转换Float为Int
- 快速提取正则表达式匹配
- 如何应用梯度的背景视图的iOS Swift应用程序
- 我如何在Swift中声明一个弱引用数组?
- 如何用SwiftUI调整图像大小?
- 如何分配一个行动UIImageView对象在Swift
- 在iOS8中使用Swift更改特定视图控制器的状态栏颜色
- 打印一个可变内存地址在swift
- 自动布局- UIButton的固有大小不包括标题插入
- 我如何使一个enum可解码在Swift?
- HTTP请求在Swift与POST方法
- 获取用户当前位置/坐标