adjustsFontForContentSizeCategory in UILabel with attributed text
Asked Answered
J

1

9

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)
Johnnyjumpup answered 9/1, 2018 at 20:23 Comment(1)
Thanks, Please answer your own question and accept it.Turmel
J
-1
public extension NSMutableAttributedString {
public func setFont(_ font: UIFont) -> NSMutableAttributedString {
    addAttribute(NSAttributedStringKey.font, value: font, range: NSRange(location: 0, length: string.count))

    return self
}

}

Johnnyjumpup answered 13/12, 2018 at 21:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.