History
Loading...
Loading...
September 4, 2025
ViewThatFits to automatically choose the best layout for available space. Wrap multiple view variations in ViewThatFits and SwiftUI will pick the first one that fits - perfect for responsive design without manual size calculations!This practice creates a hierarchy of layout options that gracefully degrade based on available space. ViewThatFits automatically selects the most appropriate layout without manual intervention.
struct AdaptiveToolbar: View {
var body: some View {
ViewThatFits(in: .horizontal) {
// First choice: Full toolbar with labels
HStack(spacing: 16) {
ToolbarButton(icon: "house", label: "Home")
ToolbarButton(icon: "magnifyingglass", label: "Search")
ToolbarButton(icon: "person", label: "Profile")
ToolbarButton(icon: "gearshape", label: "Settings")
}
// Fallback: Icons only
HStack(spacing: 12) {
Image(systemName: "house")
Image(systemName: "magnifyingglass")
Image(systemName: "person")
Image(systemName: "gearshape")
}
// Last resort: Menu button
Menu("Menu") {
Button("Home", systemImage: "house") { }
Button("Search", systemImage: "magnifyingglass") { }
Button("Profile", systemImage: "person") { }
Button("Settings", systemImage: "gearshape") { }
}
}
}
}This approach eliminates the need for complex GeometryReader calculations and manual layout switching logic. It provides better user experience across different screen sizes and orientations while keeping code clean and maintainable.