我在没有 Storyboard的情况下编码。我正在以编程方式将 UILabels 添加到 ViewControllers 中,如下所示,但不知何故字体样式保持默认。有人可以告诉我的代码有什么问题吗?谢谢!
let label: UILabel = {
let label = UILabel()
label.font = UIFont(name: "Avenir-Light", size: 20)
let attributedText = NSMutableAttributedString(string: "Text.", attributes: [NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 20)])
// Letter spacing
attributedText.addAttribute(NSAttributedStringKey.kern, value: 1.5, range: NSRange(location: 0, length: attributedText.length - 1))
// Charactor spacing
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4
attributedText.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedText.length))
label.attributedText = attributedText
return label
}()
最佳答案
属性文本的字体优先于标签本身的字体。并且您已明确定义属性文本以使用 UIFont.systemFont(ofSize: 20)
。
我建议将您的字体用于属性字符串:
let font = UIFont(name: "Avenir-Light", size: 20)
let attributedText = NSMutableAttributedString(string: "Text.", attributes: [.foregroundColor: UIColor.black, .font: font])
或者从属性字符串中省略它并使用标签的默认字体:
label.font = UIFont(name: "Avenir-Light", size: 20)
let attributedText = NSMutableAttributedString(string: "Text.", attributes: [.foregroundColor: UIColor.black])
关于Swift - 无法更改 UILabel 中的字体样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48843584/