ios - 根据 UIlabel IBDesignable 中的标题和副标题设置不同的字体
问题描述
我使用以下代码为 uilabel 创建了自定义类:
@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 创建不同的扩展
解决方案
例如,您可以添加这样的自定义style
属性:
@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
推荐阅读
- office365 - 我们可以使用一个 zap 为“n”个 Office 365 帐户创建事件吗?(Zapier-Office365)
- c++ - 为 Web 项目编译 gnu cgi 时出现编译错误
- javascript - 使用 Axios 抓取后如何将对象推送到 JSON 文件?
- c++ - std::make_pair 自动类型推断?
- benchmarking - 英特尔超路径互连 (UPI) 带宽
- python - 如何在 discord.py 中修复以下自动反应角色代码?
- github - 如何找到星数最多的分叉存储库
- powershell - 如何从 HtmlWebResponseObject 解析 JSON
- python - 如何使用来自 Pandas DataFrame 的值更新 DynamoDB 列,使用 ID 作为公共值
- amazon-web-services - 通过 aws Education 帐户为 IAMUSER 创建访问令牌的问题