Ios 根据UIlabel IBDesignable中的标题和副标题设置不同的字体
我使用以下代码为uilabel创建了自定义类:Ios 根据UIlabel IBDesignable中的标题和副标题设置不同的字体,ios,fonts,uilabel,ibdesignable,Ios,Fonts,Uilabel,Ibdesignable,我使用以下代码为uilabel创建了自定义类: @IBDesignable public class CustomUILabel: UILabel { public override func awakeFromNib() { super.awakeFromNib() configureLabel() } public override func prepareForInterfaceBuilder() { super.
@IBDesignable
public class CustomUILabel: UILabel {
public override func awakeFromNib() {
super.awakeFromNib()
configureLabel()
}
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
configureLabel()
}
func configureLabel() {
textColor = .white
font = UIFont(name: Constants.regularFontName, size: 14)
}
}
这有助于我在整个应用程序中设置字体。但我想为标题创建不同的粗体字体,为副标题创建常规字体。
只有一个文件才可以这样做吗?
或者我需要为该类型的UIlabel创建不同的扩展,例如,您可以添加如下自定义样式属性:
@IBDesignable
public class CustomUILabel: UILabel {
enum CustomUILabelStyle {
case title, subtitle
var font: UIFont? {
switch self {
case .title:
return UIFont(name: Constants.boldFontName, size: 14)
case .subtitle:
return UIFont(name: Constants.regularFontName, size: 14)
}
}
var textColor: UIColor {
switch self {
// add cases if you want different colors for different styles
default: return .white
}
}
}
var style: CustomUILabelStyle = .title {
didSet {
// update the label's properties after changing the style
if style != oldValue {
configureLabel()
}
}
}
public override func awakeFromNib() {
super.awakeFromNib()
configureLabel()
}
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
configureLabel()
}
func configureLabel() {
font = style.font
textColor = style.textColor
}
}
let label = CustomUILabel()
label.style = .title
// label.style = .subtitle
您可以这样使用它:
@IBDesignable
public class CustomUILabel: UILabel {
enum CustomUILabelStyle {
case title, subtitle
var font: UIFont? {
switch self {
case .title:
return UIFont(name: Constants.boldFontName, size: 14)
case .subtitle:
return UIFont(name: Constants.regularFontName, size: 14)
}
}
var textColor: UIColor {
switch self {
// add cases if you want different colors for different styles
default: return .white
}
}
}
var style: CustomUILabelStyle = .title {
didSet {
// update the label's properties after changing the style
if style != oldValue {
configureLabel()
}
}
}
public override func awakeFromNib() {
super.awakeFromNib()
configureLabel()
}
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
configureLabel()
}
func configureLabel() {
font = style.font
textColor = style.textColor
}
}
let label = CustomUILabel()
label.style = .title
// label.style = .subtitle
关于通过情节提要中的属性检查器设置样式,您有什么建议吗?