Dynamic Text Sizing in NSAttributedString

977 views Asked by At

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.

How can I resolve this issue?

2

There are 2 answers

0
XLE_22 On BEST ANSWER

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.

1
manubrio On

I had the same issue and I found out that settings .font in NSAttributedString results in label not resizing accordingly with accessibility settings. By removing it and adding label.font property it worked fine.