简体   繁体   中英

How to make `Label`'s font size inside `ViewCell` dependent on the device in Xamarin Forms?

So I have a few custom cells using ViewCell in my app. Inside my ViewCell are Labels . I want the font size of those labels to be dependent on the text size of the device just like how the TextCell 's text changes when you adjust the text size of your device.

Below image is using a built-in TextCell . 在此处输入图片说明

Below image is using a custom cell ViewCell 在此处输入图片说明

Im testing this in an iOS device and the text size is set to the smallest available. Whenever I change the device text size the cells using TextCell s will just automatically changed. The labels inside the ViewCell doesn't change at all. Any suggestion pointing me to the right direction is very much appreciated.

Short answer

The TextCell uses the native UITableViewCell on iOS. This native view takes the device accessibility settings into account. When you use the Xamarin Forms Label , it does not. Xamarin Forms does not support iOS Dynamic Type (yet).

Explanation

The Forms Label uses the FontSizeConverter to set the actual font size. This font size defaults to the value -1 if you don't set any value yourself. The value -1 results in the use of NamedSize.Default (see the Font class ).

When you take a look at the FontSizeConverter , if it can't parse the value as an absolute value, it will try to convert to a NamedSize value. In that case, it will use Device.GetNamedSize to get the actual size. This is done through the IPlatformServices interface, which converts these to absolute values ( see the IOSPlatformServices ).

There is also a FontExtensions class, that implements the same conversion from Named Size to an absolute value. Not very DRY at first sight, but there could be a good reason for this, that I'm not aware of.

Unfortunately, both the FontExtensions and the IOSPlatformServices don't take the accessibility options of iOS into account, but just return absolute values.

Possible solution

On iOS, you could use UIKit.UIApplication.SharedApplication.PreferredContentSizeCategory to get the current accessibility category. Based on this value, you could determine a scale for your fonts (use DynamicResource for the font sizes if you use them in XAML, so they can change at runtime).

Or take a look at SushiHangover's answer on a similar question.

See the preferredContentSizeCategory on the Apple Developer API reference .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM