Allow a user to select the text size is a must if your app wants to be accessible. IOS already make our life easier by handling most of cases nicely.
But there are cases where two design elements compete for the available space.
Let’s look on the following example:
1 2 3 4 5 6 7 8 9 10 11 |
struct ContentView: View { var body: some View { HStack { Text("Hello, world!") Spacer() Text("Today is a sunny day") } .padding() } } |
Which in default text size draws as follows:
Let’s now increase the text size:
1 2 3 4 5 6 |
struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() .dynamicTypeSize(.accessibility5) } } |
We notice that now the reading of the texts are not so clear.
Let’s try now to solve this issue by creating a view that can adapt to size category changes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
struct SizeCategoryAdaptiveStack: ViewModifier { @Environment(\.sizeCategory) var sizeCategory @ViewBuilder func body(content: Content) -> some View { if sizeCategory.isAccessibilityCategory { VStack { content } } else { HStack { content } } } } |
And update the view to use it:
1 2 3 4 5 6 7 8 9 10 11 |
struct ContentView: View { var body: some View { Group { Text("Hello, world!") Text("Today is a sunny day") } .padding() .modifier(SizeCategoryAdaptiveStack()) } } |
Which produces the following desirable UI:
I used to use the Stack in UIKit to change the axis from horizontal to vertical to support this case, but for SwiftUI I got inspired by the following resourse.
Resources:
https://swiftwithmajid.com/2019/10/09/dynamic-type-in-swiftui/
https://www.fivestars.blog/articles/adaptive-swiftui-views/