ios - 具有系统字体、粗体和字距调整的 UIButton 子类
问题描述
您必须使用属性文本来进行字距调整。但。另一方面,您无法在 IB 属性文本菜单中获取系统字体。
我如何制作(在代码中)UIButton
具有
- 系统字体,粗体粗体
- 尺寸 11
- 紧缩属性设置为 -2
理想情况下,它将从 IB 中的纯文本标题中收集按钮的文本。但是,如果必须在代码中设置文本,那很好。
class NiftyButton: UIButton {
????
}
通常我像这样初始化 UIButton .. 但我什至不知道这是否是最好的地方?(你不能在 layoutSubviews 中这样做,因为它当然会循环。)
class InitializeyButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
common()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
common()
}
func common() {
...
}
}
如何在代码中实现...
- 系统字体,粗体粗体
- 尺寸 11
- 紧缩属性设置为 -2
解决方案
这是您可以用来获得所需结果的类:
class InitializeyButton: UIButton {
@IBInspectable var spacing:CGFloat = 0 {
didSet {
updateTitleOfLabel()
}
}
override func setTitle(_ title: String?, for state: UIControl.State) {
let color = super.titleColor(for: state) ?? UIColor.black
let attributedTitle = NSAttributedString(
string: title ?? "",
attributes: [NSAttributedString.Key.kern: spacing,
NSAttributedString.Key.foregroundColor: color,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: self.titleLabel?.font.pointSize ?? 11, weight: .bold) ])
super.setAttributedTitle(attributedTitle, for: state)
}
private func updateTitleOfLabel() {
let states:[UIControl.State] = [.normal, .highlighted, .selected, .disabled]
for state in states {
let currentText = super.title(for: state)
self.setTitle(currentText, for: state)
}
}
}
推荐阅读
- r - nlme 中的多重随机效应
- sql - 表“test.grouped”不存在
- python - 分隔符问题,pd.read_csv
- gitlab - 使用 gitlab.com 托管的 Gitlab,如何在 Prometheus 中获取诸如“提交次数”之类的指标?
- hyperledger-fabric - 我们可以自定义交易类型或在链码中添加一些代码格式来阻止以确定交易类型吗?
- reporting-services - Power BI:关于隐私问题的建议
- python - 从 seaborn 图中删除图例标题
- python-3.x - 如何使用 Python API 知道我在 Firestore 中有哪些集合
- python - 如何在 python 中每 2 分钟重置并重新运行此代码?while 循环对我来说失败了
- java - Spring Boot:配置自定义 MethodSecurityExpressionOperations?