I am trying to implement automatic font scaling on labels in iOS and basically it does not work. Even worse, the app quits. The code is based on the Apple documentation here.
Here is the code below:
setDynamicFont (extends label As MobileLabel)
Declare Function NSClassFromString Lib "Foundation" (className As CFStringRef) As Ptr
Declare Function preferredFontForTextStyle Lib "UIKit.framework" selector "preferredFontForTextStyle:" (obj_id As ptr, mode As textStyle) As ptr
Dim fontPtr As ptr
fontPtr = preferredFontForTextStyle(NSClassFromString("UIFont"), textStyle.body)
Declare sub setFont lib "UIKit.framework" selector "setFont:" (obj_ref as ptr, fontRef as ptr)
setFont(label.Handle, fontPtr)
Declare Sub setAdjustsFontForContentSizeCategory Lib "UIKit.framework" Selector "adjustsFontForContentSizeCategory:" (obj_ref as ptr, value as Boolean)
setAdjustsFontForContentSizeCategory label.Handle, True
The app stops working here → fontPtr = preferredFontForTextStyle(NSClassFromString(“UIFont”), textStyle.body)
I think that the issue could be linked to textStyle. I have some difficulties to understand what it is exactly.
From the Apple documentation here, it seems to be an enumeration. After looking for some more information, I managed to find the constants on the Xamarin documentation page dedicated to TextStyle. Still it does not work.
Could TextStyle be something else ? Or is there a mistake in my code I can not see ?
Declare sub setAdjustsFontSizeToFitWidth lib "UIKit.framework" selector "setAdjustsFontSizeToFitWidth:" (id as ptr, value as Boolean)
setAdjustsFontSizeToFitWidth label.handle, True
EDIT:
You might actually be looking for something else than the code I posted.
Please advise:
You want the font in a label to adapt based on the length of the text to display (the code I posted)
You want the font to adapt to the user’s settings such as for visual impairments
I had a look at your great iOSDesignExtensions, but what you are suggesting is a little bit different from automatic font scaling because your method adjusts the font size to fit a label width.
But, in my case, automatic font scaling is related to Accessibility. In iOS, the user can choose the font to be small or very large for easier readability. By default, a UILabel does not take the user’s setting into account. That is the reason why the developer has to implement automatic font scaling with the code below in Swift.