What is the difference between `FlowLayout` and `WrapHStack` for wrapping tag-style views in SwiftUI?
Test your knowledge:
Explanation & Code
FlowLayout uses the Layout protocol (iOS 16+) — SwiftUI's official first-party layout system. You implement sizeThatFits (return required size given a proposal) and placeSubviews (position children in final bounds). It's clean, zero-boilerplate, and participates correctly in the layout system.
WrapHStack is a View, not a Layout. It measures its own width with GeometryReader and positions children manually using alignmentGuide inside a ZStack. Height is reported via a PreferenceKey two-pass trick: render → measure → resize with @State var totalHeight.
FlowLayout | WrapHStack | |
|---|---|---|
| Approach | Layout protocol | View + GeometryReader |
| Width source | Layout proposal | GeometryReader (actual rendered) |
| Height reporting | Returned from sizeThatFits | Measured via PreferenceKey |
Works in ScrollView | ❌ Unreliable | ✅ Reliable |
| Accepts any content | ✅ Yes | ❌ Needs RandomAccessCollection |
| Spacing configurable | ✅ Both axes | ❌ Row spacing hardcoded |
| iOS version | iOS 16+ | Any |
Rate your understanding: