How do you make a UISegmentedControl follow dynamic type?

I have started applying dynamic type and preferred fonts to my app. The only part of the view controller that doesn't conform is a pair of segmented controls that stay stubbornly small when the labels etc are all expanding with the larger text slider in settings. How can I make the segmented control match the rest of the app?

Replies

I fear that only applies to text, not control.


For controls, you should probably have to adapt programmatically.


See Apple's doc: h ttps://developer.apple.com/documentation/uikit/uifont/getting_a_scaled_font

Dynamic Type allows the user to choose the size of textual content displayed on the screen

Yes, I should have specified that the font stays small in the segmented controls, while the buttons and labels adapt to the settings

SUrprising in fact.


Of course, you can turn around it (until you find how to make it dynamic), with the following :


let font = UIFont.systemFont(ofSize: 16)          // Compute the right size
segmentedControl.setTitleTextAttributes([NSAttributedStringKey.font: font], for: .normal)


This could help as well

h ttps://stackoverflow.com/questions/32155530/custom-font-in-uisegmentedcontrol-disable-adjustsfontsizetofitwidth/34754939#34754939

I put these lines in the viewDidLoad:

        let font = UIFont.preferredFont(forTextStyle: .body)
        srceUnitSeg.setTitleTextAttributes([NSAttributedStringKey.font: font], for: .normal)
        destUnitSeg.setTitleTextAttributes([NSAttributedStringKey.font: font], for: .normal)

Thanks, the user gets the right font when the app is loaded.
Now I want to work out how to catch that notification when the user changes preferred font size with the app running.

There's a UIContentSizeCategoryDidChangeNotification that you can listen for.


https://developer.apple.com/documentation/uikit/uicontentsizecategorydidchangenotification

        updateNonautoDynamicFonts()
        NotificationCenter.default.addObserver(forName: .UIContentSizeCategoryDidChange,
                                               object: nil,  // Source of notification; nil means all sources
                                               queue: OperationQueue.main) { [weak self] _ in
            self?.updateNonautoDynamicFonts()
        }

I put the code above in viewDidLoad, and in updateNonautoDynamicFonts I have slightly different code from my earlier post:

        let font = UIFont.preferredFont(forTextStyle: .body)
        self.srceUnitSeg.font = font
        self.destUnitSeg.font = font