swiftui-layout-components
dpearson2699/swift-ios-skills
Build SwiftUI layouts with stacks, grids, lists, forms, and controls for iOS 17+.
What is swiftui-layout-components?
Provides patterns and best practices for SwiftUI layout components including VStack/HStack/ZStack, LazyVGrid/LazyHGrid, List with sections, ScrollView with ScrollPosition, Form with validation, and interactive controls like Toggle/Picker/Slider. Use when building data-driven layouts, collection views, settings screens, search interfaces, or overlay UI.
- Build vertical, horizontal, and layered layouts with standard and lazy stacks
- Create adaptive and fixed-column grids for galleries and dense selections
- Implement feed-style lists with sections, swipe actions, and scroll-to-top patterns
- Use ScrollView with ScrollPosition for programmatic scroll control and edge effects
- Build structured forms with validation, focus management, and grouped controls
- Add native search UI with searchable modifier and debounced async results
How to install swiftui-layout-components
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill swiftui-layout-components- iOS 17 or later (iOS 26 for some advanced features like scrollEdgeEffectStyle)
- Swift 6.3 or compatible version
- Basic SwiftUI knowledge
How to use swiftui-layout-components
- 1.Choose a layout container: VStack/HStack for small fixed content, LazyVStack/LazyHStack for large collections in ScrollView, LazyVGrid for grids
- 2.For lists, use List with .listStyle(.plain) for feeds or .insetGrouped for settings
- 3.For forms, wrap controls in Form with Section groups and bind to @State or @Binding
- 4.Add search with .searchable modifier and use .searchScopes for multiple modes
- 5.Use ScrollPosition for programmatic scroll control and .scrollTargetLayout() for reliable jump-to-id behavior
- 6.Apply .scrollContentBackground(.hidden) and custom backgrounds for themed surfaces
- 7.Manage keyboard focus in input forms with @FocusState
Use cases
- Building settings screens with grouped toggles, pickers, and sliders
- Creating media galleries and icon pickers with adaptive grid layouts
- Implementing feed layouts with pull-to-refresh and scroll-to-bottom messaging
- Adding search interfaces with scoped search and async filtering
- Building data-driven lists with sections, navigation, and swipe actions
- iOS app developers targeting iOS 17+
- SwiftUI developers building forms and settings screens
- Engineers creating collection and gallery views
- Developers implementing search and filtering interfaces
swiftui-layout-components FAQ
Use regular VStack/HStack for small, fixed-size content like headers and toolbars. Use LazyVStack/LazyHStack inside ScrollView for large or unknown-size collections, feeds, and chat messages to avoid rendering all children upfront.
Use LazyVGrid with GridItem(.adaptive(minimum: 120, maximum: 1024)) to let columns adjust automatically. For a fixed column count, use Array(repeating: GridItem(.flexible()), count: 3).
Use ScrollView with LazyVStack, apply .scrollTargetLayout(), bind ScrollPosition to @State, and call scrollPosition.scrollTo(edge: .bottom) inside onChange when new messages arrive.
Use .scrollContentBackground(.hidden) on the List, then apply your custom background with .background(Color.myTheme) or a gradient.
Use List for built-in row reuse, selection, and accessibility in settings and simple feeds. Use ScrollView + LazyVStack for custom layouts, mixed content types, or horizontal scrolling.
Full instructions (SKILL.md)
Source of truth, from dpearson2699/swift-ios-skills.
name: swiftui-layout-components description: "Build SwiftUI layouts using stacks, grids, lists, scroll views, forms, and controls. Covers VStack/HStack/ZStack, LazyVGrid/LazyHGrid, List with sections and swipe actions, ScrollView with ScrollPosition, Form with validation, Toggle/Picker/Slider, .searchable, and overlay patterns. Use when building data-driven layouts, collection views, settings screens, search interfaces, or transient overlay UI."
SwiftUI Layout & Components
Layout and component patterns for SwiftUI apps targeting iOS 26+ with Swift 6.3. Covers stack and grid layouts, list patterns, scroll views, forms, controls, search, and overlays. Patterns are backward-compatible to iOS 17 unless noted.
Contents
- Layout Fundamentals
- Grid Layouts
- List Patterns
- ScrollView
- Form and Controls
- Searchable
- Overlay and Presentation
- Common Mistakes
- Review Checklist
- References
Layout Fundamentals
Standard Stacks
Use VStack, HStack, and ZStack for small, fixed-size content. They render all children immediately.
VStack(alignment: .leading) {
Text(title).font(.headline)
Text(subtitle).font(.subheadline).foregroundStyle(.secondary)
}
Lazy Stacks
Use LazyVStack and LazyHStack inside ScrollView for large or dynamic collections. They create child views on demand as they scroll into view.
ScrollView {
LazyVStack {
ForEach(items) { item in
ItemRow(item: item)
}
}
.padding(.horizontal)
}
When to use which:
- Non-lazy stacks: Small, fixed content (headers, toolbars, forms with few fields)
- Lazy stacks: Large or unknown-size collections, feeds, chat messages
Grid Layouts
Use LazyVGrid for icon pickers, media galleries, and dense visual selections. Use .adaptive columns for layouts that scale across device sizes, or .flexible columns for a fixed column count.
// Adaptive grid -- columns adjust to fit
let columns = [GridItem(.adaptive(minimum: 120, maximum: 1024))]
LazyVGrid(columns: columns) {
ForEach(items) { item in
ThumbnailView(item: item)
.aspectRatio(1, contentMode: .fit)
}
}
// Fixed 3-column grid
let columns = Array(repeating: GridItem(.flexible(minimum: 100), spacing: 4), count: 3)
LazyVGrid(columns: columns, spacing: 4) {
ForEach(items) { item in
ThumbnailView(item: item)
}
}
Use .aspectRatio for cell sizing. Never place GeometryReader inside lazy containers -- it forces eager measurement and defeats lazy loading. Use .onGeometryChange (iOS 16+) if you need to read dimensions.
See references/grids.md for full grid patterns and design choices.
List Patterns
Use List for feed-style content and settings rows where built-in row reuse, selection, and accessibility matter.
List {
Section("General") {
NavigationLink("Display") { DisplaySettingsView() }
NavigationLink("Haptics") { HapticsSettingsView() }
}
Section("Account") {
Button("Sign Out", role: .destructive) { }
}
}
.listStyle(.insetGrouped)
Key patterns:
.listStyle(.plain)for feed layouts,.insetGroupedfor settings.scrollContentBackground(.hidden)+ custom background for themed surfaces.listRowInsets(...)and.listRowSeparator(.hidden)for spacing and separator control- Edge scrolling: use
List+ScrollPositionwith.scrollPosition($scrollPosition)for top/bottom scroll actions - Item or section jumps: use
ScrollView+ lazy stacks with.scrollTargetLayout()and stable targets for reliable jump-to-id behavior - Use
.refreshable { }for pull-to-refresh feeds - Use
.contentShape(Rectangle())on rows that should be tappable end-to-end - For layout review or migration guidance, lead with container choice and constraints; keep code snippets tiny, and defer spring, transition, and timing choices to
swiftui-animation
iOS 26: Apply .scrollEdgeEffectStyle(.soft, for: .top) for modern scroll edge effects.
See references/list.md for full list patterns including feed lists with scroll-to-top.
ScrollView
Use ScrollView with lazy stacks when you need custom layout, mixed content, or horizontal scrolling.
ScrollView(.horizontal, showsIndicators: false) {
LazyHStack {
ForEach(chips) { chip in
ChipView(chip: chip)
}
}
}
ScrollPosition: Enables declarative, bidirectional scroll position tracking and programmatic scrolling.
@State private var scrollPosition = ScrollPosition(edge: .bottom)
ScrollView {
LazyVStack {
ForEach(messages) { message in
MessageRow(message: message)
}
}
.scrollTargetLayout()
}
.scrollPosition($scrollPosition)
.onChange(of: messages.last?.id) {
withAnimation { scrollPosition.scrollTo(edge: .bottom) }
}
See references/scrollview.md for full ScrollPosition patterns including scroll-to-id and user-scroll detection.
safeAreaInset(edge:) pins content (input bars, toolbars) above the keyboard without affecting scroll layout.
iOS 26 additions:
.scrollEdgeEffectStyle(.soft, for: .top)-- fading edge effect.backgroundExtensionEffect()-- mirror/blur at safe area edges (use sparingly, one per screen).safeAreaBar(edge:)-- attach bar views that integrate with scroll effects
See references/scrollview.md for full scroll patterns and iOS 26 edge effects.
Form and Controls
Form
Use Form for structured settings and input screens. Group related controls into Section blocks.
Form {
Section("Notifications") {
Toggle("Mentions", isOn: $prefs.mentions)
Toggle("Follows", isOn: $prefs.follows)
}
Section("Appearance") {
Picker("Theme", selection: $theme) {
ForEach(Theme.allCases, id: \.self) { Text($0.title).tag($0) }
}
Slider(value: $fontScale, in: 0.5...1.5, step: 0.1)
}
}
.formStyle(.grouped)
.scrollContentBackground(.hidden)
Use @FocusState to manage keyboard focus in input-heavy forms. Wrap in NavigationStack only when presented standalone or in a sheet.
Controls
| Control | Usage |
|---|---|
Toggle | Boolean preferences |
Picker | Discrete choices; .segmented for 2-4 options |
Slider | Numeric ranges with visible value label |
DatePicker | Date/time selection |
TextField | Text input with .keyboardType, .textInputAutocapitalization |
Bind controls directly to @State, @Binding, or @AppStorage. Group related controls in Form sections. Use .disabled(...) to reflect locked or inherited settings. Use Label inside toggles to combine icon + text when it adds clarity.
// Toggle sections
Form {
Section("Notifications") {
Toggle("Mentions", isOn: $preferences.notificationsMentionsEnabled)
Toggle("Follows", isOn: $preferences.notificationsFollowsEnabled)
}
}
// Slider with value text
Section("Font Size") {
Slider(value: $fontSizeScale, in: 0.5...1.5, step: 0.1)
Text("Scale: \(String(format: "%.1f", fontSizeScale))")
}
// Picker for enums
Picker("Default Visibility", selection: $visibility) {
ForEach(Visibility.allCases, id: \.self) { option in
Text(option.title).tag(option)
}
}
Avoid .pickerStyle(.segmented) for large sets; use menu or inline styles. Don't hide labels for sliders; always show context.
See references/form.md for full form examples.
Searchable
Add native search UI with .searchable. Use .searchScopes for multiple modes and .task(id:) for debounced async results.
@MainActor
struct ExploreView: View {
@State private var searchQuery = ""
@State private var searchScope: SearchScope = .all
@State private var isSearching = false
@State private var results: [SearchResult] = []
var body: some View {
List {
if isSearching {
ProgressView()
} else {
ForEach(results) { result in
SearchRow(result: result)
}
}
}
.searchable(
text: $searchQuery,
placement: .navigationBarDrawer(displayMode: .always),
prompt: Text("Search")
)
.searchScopes($searchScope) {
ForEach(SearchScope.allCases, id: \.self) { scope in
Text(scope.title)
}
}
.task(id: searchQuery) {
await runSearch()
}
}
private func runSearch() async {
guard !searchQuery.isEmpty else {
results = []
return
}
isSearching = true
defer { isSearching = false }
try? await Task.sleep(for: .milliseconds(250))
results = await fetchResults(query: searchQuery, scope: searchScope)
}
}
Show a placeholder when search is empty. Debounce input to avoid overfetching. Keep search state local to the view. Avoid running searches for empty strings.
Overlay and Presentation
Use .overlay(alignment:) for transient UI (toasts, banners) without affecting layout.
struct AppRootView: View {
@State private var toast: Toast?
var body: some View {
content
.overlay(alignment: .top) {
if let toast {
ToastView(toast: toast)
.transition(.move(edge: .top).combined(with: .opacity))
.onAppear {
Task {
try? await Task.sleep(for: .seconds(2))
withAnimation { self.toast = nil }
}
}
}
}
}
}
Prefer overlays for transient UI rather than embedding in layout stacks. Use transitions and short auto-dismiss timers. Keep overlays aligned to a clear edge (.top or .bottom). Avoid overlays that block all interaction unless explicitly needed. Don't stack many overlays; use a queue or replace the current toast.
For modal routing, sheet detents, and full-screen presentation policy, hand off to the swiftui-navigation skill.
Common Mistakes
- Using non-lazy stacks for large collections -- causes all children to render immediately
- Placing
GeometryReaderinside lazy containers -- defeats lazy loading - Using array indices as
ForEachIDs -- causes incorrect diffing and UI bugs - Nesting scroll views of the same axis -- causes gesture conflicts
- Heavy custom layouts inside
Listrows -- useScrollView+LazyVStackinstead - Missing
.contentShape(Rectangle())on tappable rows -- tap area is text-only - Hard-coding frame dimensions for sheets -- use
.presentationSizinginstead - Running searches on empty strings -- always guard against empty queries
- Mixing
ListandScrollViewin the same hierarchy -- gesture conflicts - Using
.pickerStyle(.segmented)for large option sets -- use menu or inline styles - Hard-coding
spacing:on stacks and grids by default -- omit to get platform-adaptive spacing; only specify for intentional tight (0–4pt) or wide gaps
Review Checklist
-
LazyVStack/LazyHStackused for large or dynamic collections - Stable
IdentifiableIDs on allForEachitems (not array indices) - No
GeometryReaderinside lazy containers -
Liststyle matches context (.plainfor feeds,.insetGroupedfor settings) -
Formused for structured input screens (not custom stacks) -
.searchabledebounces input with.task(id:) -
.refreshableadded where data source supports pull-to-refresh - Overlays use transitions and auto-dismiss timers
-
.contentShape(Rectangle())on tappable rows -
@FocusStatemanages keyboard focus in forms - Stack/grid
spacing:omitted unless a specific value is required
References
- Grid patterns: references/grids.md
- List and section patterns: references/list.md
- ScrollView and lazy stacks: references/scrollview.md
- Form patterns: references/form.md
- Architecture and state management: see
swiftui-patternsskill - Navigation patterns: see
swiftui-navigationskill
Related skills
More from dpearson2699/swift-ios-skills and the wider catalog.

swiftui-liquid-glass
Implement SwiftUI Liquid Glass effects for iOS 26+ with glass buttons, morphing transitions, and interactive controls.

swiftui-navigation
SwiftUI navigation patterns: NavigationStack, NavigationSplitView, sheets, tabs, and deep linking for iOS 17+.

swiftui-patterns
Build and review SwiftUI views with modern MV architecture, state management, and composition patterns.

swiftui-performance
Audit and optimize SwiftUI runtime performance—diagnose slow rendering, janky scrolling, and excessive view updates.

swiftui-uikit-interop
Bridge UIKit and SwiftUI bidirectionally with representables, hosting controllers, and state synchronization.

swiftui-webkit
Embed and control web content in SwiftUI using native WebKit APIs for iOS 26+.