使用 swift,我尝试使用这段代码使按钮变圆,并且它有效:
button.layer.borderColor = UIColor.grayColor().CGColor
button.layer.borderWidth = 1
button.layer.cornerRadius = 8
不幸的是,我有很多按钮,我想知道是否有一种方法可以让所有按钮都变成圆形,而无需每次都对上面的代码进行“复制和粘贴”。
最佳答案
您可以通过 UIAppearance 执行此操作,它是一个代理,允许您为 UIKit
类的所有对象配置属性。
首先,由于 UIAppearance
作用于 UIView
本身的属性,而您要控制的属性位于按钮层上,因此您需要将其暴露给外观:
@objc extension UIButton {
dynamic var borderColor: UIColor? {
get {
if let cgColor = layer.borderColor {
return UIColor(CGColor: cgColor)
}
return nil
}
set { layer.borderColor = newValue?.CGColor }
}
dynamic var borderWidth: CGFloat {
get { return layer.borderWidth }
set { layer.borderWidth = newValue }
}
dynamic var cornerRadius: CGFloat {
get { return layer.cornerRadius }
set { layer.cornerRadius = newValue }
}
}
在 Swift
中,dynamic
关键字指示编译为属性生成 getter 和 setter,以便将其标识为可配置的 UIAppearance
, (请参阅 SO question 和 Apple's documentation 了解更多详情)。
然后您可以在 UIButton
类的 ui 外观上设置属性:
UIButton.appearance().borderColor = UIColor.grayColor();
UIButton.appearance().borderWidth = 2;
UIButton.appearance().cornerRadius = 20;
您应该在应用程序启动期间进行配置,因为在将 View 添加到窗口时外观会发生变化(请参阅UIAppearance
文档中的注释)。
如果您只想为您的类中的某些按钮提供这些默认属性,您可以子类化 UIButton
,并使用该类的外观而不是 UIButton
。例如:
class MyButton: UIButton {}
...
MyButton.appearance().borderColor = UIColor.grayColor();
MyButton.appearance().borderWidth = 2;
MyButton.appearance().cornerRadius = 20;
只会将样式应用于 MyButton
类的按钮。这允许您通过简单地继承 UIButton
并处理子类的外观来为您的类中的按钮定义不同的外观。
关于ios - 使所有按钮变圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34797095/