Leave a rating/review
Notes: 35. Intro to Size Classes
Nice reference for size classes: https://useyourloaf.com/blog/size-classes/
As you saw in the previous episode, our Leaderboard view is looking good, except in portrait, the X button overlaps the leaderboard text.
To fix this, we want to be able to detect when we are in this case where there’s not enough space, and if we are, we want to left justify the text, so they don’t overlap. Otherwise, if there is plenty of room, we’ll keep the leaderboard text centered like it is now.
But how can we detect when we’re in this case where we don’t have enough space?
Think back to the episode on environment property wrappers, where you learned how you can read certain variables from the app’s environment - such as whether the app is in light or dark mode.
Well, there’s some more data available to you in the environment, for the app’s size class.
Size Classes are a way for Apple to let you know if your app currently has a “regular” amount of space available for layout, or if you currently have a “compact” amount of space.
Here are a couple examples. We’re going to use the iPhone Plus and Max Models as an example, and in a minute I’ll show you how you can find what the results will be for other device sizes.
For the iPhone and Max Models, if your device is in portrait mode, you have plenty of space horizontally, so the size class is regular. But you only have a small amount of vertical space, so the size class for that is compact.
In Portait mode, it’s exactly the oppsoite. You only have a small amount of horizontal space, so that is compact. But you have plenty of vertical space, so that is regualar.
Let’s see how we can use this to make the layout look great depending on how much screen space we have available.
A blog I like called UseYourLoaf.com has a handy refernce chart that shows you what the size classes look like for various device layouts.
Show them the iPod touch size classes and show it’s a little different in landscape, but we can still use it to get what we want.
Add to LeaderboardView.swift’s HeaderView:
@Environment(\.verticalSizeClass) var verticalSizeClass
@Environment(\.horizontalSizeClass) var horizontalSizeClass
Add to the body, right under BigBoldText:
HStack {
BigBoldText(text: "Leaderboard")
if verticalSizeClass == .regular && horizontalSizeClass == .compact {
Spacer()
}
}
Show it working in the preview, but fix by adding some leading space:
.padding(.leading)