SwiftUI Grid: fixed vs flexible vs adaptive
If you take advantage of SwiftUI’s grid, you can create really nice layouts. However, if you use grid without knowing the exact difference between grid types, you may have a hard time. So it is better to use it when there is no confusing part at all. Today I want to talk about the difference between .fixed, .flexible and .adaptive.
fixed
Fixed Characteristics
- fixed size never adapts.
- If there’s not enough space, fixed size can go out of screen.
Example 1)
Now you have three columns defined. What do you think is going to happen?
No matter what, column numbers will never change.
Example 2)
What do you expect? As I told you, if there’s not enough space, fixed size can go out of the screen.
flexible
flexible Characteristics
- flexible columns try its best to remain with the columns you defined.
- But if there’s not enough space, flexible creates a new row.
Example 1)
What will happen in your opinion?
If there’s enough space, all columns will be three.
Example 2)
Each row must have 6 columns. But would it work as it is expected?
Answer is NO.
Even if you defined each row with 6 columns, each row has 4 columns at most. Why is this happening? It’s because there’s not available space for flexible columns to fit in.
adaptive
adaptive Characteristics
- adaptive won’t follow the column numbers you defined.
- adaptive columns always try to fill the remaining space.
Example1)
I told you “adaptive won’t follow the column numbers you defined.” So, wait for one second and think about it. How views would be drawn?
See what happens. Even if you defined one row to have two columns, adaptive items fill the remaining space. As a result, each row has four columns now.
Where ‘adaptive’ is used for?
It’s great when you support multiple screens. Mac App, IPad Apps, WatchApps. It’s also great when you handle orientation changes. Landscape and Portrait Mode as for an example.
Conclusion
Fixed
Characteristics
- fixed size never adapts.
- If there’s not enough space, fixed size can go out of screen.
flexible
Characteristics
- flexible columns try its best to remain with the columns you defined.
- But if there’s not enough space, flexible creates a new row.
adaptive
Characteristics
- adaptive won’t follow the column numbers you defined.
- adaptive columns always try to fill the remaining space.