In this lesson, you will learn how to build layouts that gracefully adapt when users change their system-wide font size settings in their device accessibility preferences.
When a user increases their "Text Size" or "Display Zoom" in iOS or Android settings, your app's hard-coded pixel values can lead to text being cut off or layouts breaking. To solve this, React Native provides the PixelRatio API, specifically the getFontScale() method, which tells you the multiplier currently set by the user.
Why Scaling Matters
If you set a font size of 16, a user with "Extra Large" text settings might actually see that text rendered at 20 or higher. If your container height is fixed, that text will clip or disappear. By multiplying your base sizes by the current scale factor, your UI remains proportional and readable.
Implementing Dynamic Scaling
You can create a helper function to scale your dimensions based on the system's preference:
import { PixelRatio, StyleSheet } from 'react-native';
const fontScale = PixelRatio.getFontScale();
const normalize = (size) => {
return size * fontScale;
};
const styles = StyleSheet.create({
title: {
fontSize: normalize(20), // Automatically adjusts to user settings
paddingVertical: normalize(10),
},
});
Best Practices for Layouts
- Avoid Fixed Heights: Whenever possible, avoid setting a fixed
heighton containers holding text. Usepaddingorflexinstead, allowing the container to expand naturally as the text grows. - Test Frequently: Since you’ve already mastered Debugging UI Layout Hierarchies, use your emulator’s accessibility settings to toggle font sizes while the app is running. This allows you to verify that your layout doesn't break in "Large Text" mode.
- Responsive Spacing: Don’t just scale fonts; consider scaling vertical margins or paddings if the text inside them is also scaled. This maintains the "rhythm" of your design regardless of the user's accessibility needs.
By normalizing your values, you ensure your app is not just functional, but inclusive for every user.
Key Takeaway: Always multiply your base font sizes by PixelRatio.getFontScale() to ensure your layout elements expand proportionally with the user's system-level accessibility settings.