Swift、Xcode 6.4 中可重复使用的 UILabel 样式
Reusable UILabel styles in Swift, Xcode 6.4
有没有一种比制作覆盖 UILabel 的自定义 类 更简单的 UILabel 样式设置方法。目前我需要一堆不同字体大小和文本颜色的样式。
我不知道这是个好习惯...但你可以这样:
extension UILabel {
@IBInspectable var myStyle: String {
set {
switch newValue {
case "style1":
self.font = UIFont.systemFontOfSize(17)
self.textColor = UIColor.blackColor()
case "style2":
self.font = UIFont.boldSystemFontOfSize(32)
self.textColor = UIColor.redColor()
default:
break
}
}
get {
return ""
}
}
}
也许,你应该用 @IBDesignable
定义一个子类。因为这在 IB 中显示了更好的预览。并且,您可以使用 Editor > Size To Fit
或 IB 中的自动布局功能。
@IBDesignable class StyledLabel: UILabel {
@IBInspectable var myStyle: String = "" {
didSet {
switch self.myStyle {
case "style1":
self.font = UIFont.systemFontOfSize(17)
self.textColor = UIColor.blackColor()
case "style2":
self.font = UIFont.boldSystemFontOfSize(32)
self.textColor = UIColor.redColor()
default:
break
}
}
}
}
有没有一种比制作覆盖 UILabel 的自定义 类 更简单的 UILabel 样式设置方法。目前我需要一堆不同字体大小和文本颜色的样式。
我不知道这是个好习惯...但你可以这样:
extension UILabel {
@IBInspectable var myStyle: String {
set {
switch newValue {
case "style1":
self.font = UIFont.systemFontOfSize(17)
self.textColor = UIColor.blackColor()
case "style2":
self.font = UIFont.boldSystemFontOfSize(32)
self.textColor = UIColor.redColor()
default:
break
}
}
get {
return ""
}
}
}
也许,你应该用 @IBDesignable
定义一个子类。因为这在 IB 中显示了更好的预览。并且,您可以使用 Editor > Size To Fit
或 IB 中的自动布局功能。
@IBDesignable class StyledLabel: UILabel {
@IBInspectable var myStyle: String = "" {
didSet {
switch self.myStyle {
case "style1":
self.font = UIFont.systemFontOfSize(17)
self.textColor = UIColor.blackColor()
case "style2":
self.font = UIFont.boldSystemFontOfSize(32)
self.textColor = UIColor.redColor()
default:
break
}
}
}
}