简体   繁体   中英

Swift - Can't change Font Style in UILabel

I'm coding without storyboard. I'm adding UILabels into ViewControllers programmatically like below but somehow font style stays with the default. Can someone tell what the problem is with my codes? Thank you!

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

}()

The font for the attributed text takes priority over the font for the label, itself. And you have explicitly defined your attributed text to use UIFont.systemFont(ofSize: 20) .

I'd suggest either using your font for the attributed string:

let font = UIFont(name: "Avenir-Light", size: 20)
let attributedText = NSMutableAttributedString(string: "Text.", attributes: [.foregroundColor: UIColor.black, .font: font])

Or omitting it from the attributed string and use the label's default font:

label.font = UIFont(name: "Avenir-Light", size: 20)
let attributedText = NSMutableAttributedString(string: "Text.", attributes: [.foregroundColor: UIColor.black])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM