Dynamic Text Sizing in NSAttributedString

Viewed 37

I'm trying to support Large Font Accessibility in the app. There are places where we are using NSAttributedString to set the attributedText of a UILabel.

On UILabel, we've set adjustsFontForContentSizeCategory = true. Also, in the attributes, we're using UIFontMetrics to allow the label to adapt to the size changes.

UIFontMetrics(forTextStyle: .caption2).scaledFont(for: UIFont.systemFont(ofSize: 11))

Issue:

When I run the app, the UILabel displays the attributedText as per the device's current Size Category. But, when I change the size category from device's accessibility settings, the UILabel is not updated accordingly.

Can someone please help me resolve this issue?

1 Answers

Can someone please help me resolve this issue?

I hope that's the proper way you used because it's definitely the method I abide by (and it works). ‍

I created a blank project in Interface Builder (Xcode 13.4.1) as follows: enter image description here

I code the UILabel text as NSAttributedString to follow your pattern plus some other stuff for the Dynamic Type feature:

class ViewController: UIViewController {

    @IBOutlet weak var myLabel: UILabel!

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        let myText = NSAttributedString(string: "hello C.A.P.T.I.O.N. 2")
        myLabel.attributedText = myText
    
        myLabel.adjustsFontForContentSizeCategory = true
        myLabel.font = UIFontMetrics(forTextStyle: .caption2).scaledFont(for: UIFont.systemFont(ofSize: 11.0))
    }
}

Finally, I get this result on an iPhoneProMax (15.6.1):

enter image description here

I don't know what's inside your code but, following this rationale, you're now able to use the Dynamic Text Sizing in NSAttributedString.

Related