Swift - 无法在UILabel中更改字体样式

时间:2018-02-17 16:46:06

标签: swift

我在没有故事板的情况下编码。我正在以编程方式将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

}()

1 个答案:

答案 0 :(得分:3)

属性文本的字体优先于标签的字体本身。并且您已明确定义了归因文本以使用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])