简体   繁体   中英

adjustsFontForContentSizeCategory in UILabel with attributed text

I thought I would save others hours of debugging and say that setting adjustsFontForContentSizeCategory to true has no affect on labels you set the attributedText value of (at least in tableview cell labels).

Luckily the solution is to set the font on the attributed string yourself. I wrote a small utility extension:

public extension NSMutableAttributedString {
    public func setFont(_ font: UIFont) -> NSMutableAttributedString {
        addAttribute(NSAttributedStringKey.font, value: font, range: NSRange(location: 0, length: string.count))

        return self
    }
}

Where you set the attributedText property you would call

@IBOutlet weak var myLabel: UILabel!

var myAttributedString: NSAttributedString = .....

myLabel.attributedText = NSMutableAttributedString(attributedString: myAttributedString).setFont(myLabel.font)
public extension NSMutableAttributedString {
public func setFont(_ font: UIFont) -> NSMutableAttributedString {
    addAttribute(NSAttributedStringKey.font, value: font, range: NSRange(location: 0, length: string.count))

    return self
}

}

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