Swiftui Layout Components

作者 dpearson26998d90fd121a26無授權條款1.1K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫2 個月前更新

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 and scroll-driven reveal surfaces, Form with validation, Toggle/Picker/Slider, .searchable, and overlay patterns. Use when building data-driven layouts, collection views, paged detail reveals, settings screens, search interfaces, or transient overlay UI.

AI 產生的概覽

用於建構 SwiftUI 佈局的參考指南,涵蓋堆疊、網格、清單、捲動視圖、表單、搜尋與覆疊。

功能
此技能提供 iOS 應用程式的 SwiftUI 佈局與元件模式,涵蓋 VStack/HStack/ZStack、惰性堆疊、LazyVGrid/LazyHGrid、含區段的 List、搭配 ScrollPosition 的 ScrollView、含控制項的 Form、.searchable 以及覆疊呈現。內容包含程式碼片段、常見錯誤清單與審查清單,並附上網格、清單、捲動視圖與表單的參考檔案。產出的是指引與程式碼範例,而非可直接執行的成品。
適用情境
適用於建構資料驅動佈局、集合或圖庫檢視、設定與輸入畫面、搜尋介面、捲動驅動的揭露介面,或 SwiftUI 中的暫時性覆疊 UI。也適合審查或移轉現有的 SwiftUI 佈局程式碼。
執行需求
無需指令碼或套件,僅為說明與參考文件。指南以 iOS 26+ 與 Swift 6.3 的 SwiftUI 為目標,除特別註明外,模式可回溯相容至 iOS 17。

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

Standard Stacks

Use VStack, HStack, and ZStack for small, fixed-size content. They render all children immediately.

swift
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.

swift
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.

swift
// Adaptive grid -- columns adjust to fitlet columns = [GridItem(.adaptive(minimum: 120, maximum: 1024))]
LazyVGrid(columns: columns) {    ForEach(items) { item in        ThumbnailView(item: item)            .aspectRatio(1, contentMode: .fit)    }}
swift
// Fixed 3-column gridlet 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 [blocked] 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.

swift
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, .insetGrouped for settings
  • .scrollContentBackground(.hidden) + custom background for themed surfaces
  • .listRowInsets(...) and .listRowSeparator(.hidden) for spacing and separator control
  • Edge scrolling: use List + ScrollPosition with .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 [blocked] 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.

swift
ScrollView(.horizontal, showsIndicators: false) {    LazyHStack {        ForEach(chips) { chip in            ChipView(chip: chip)        }    }}

ScrollPosition: Enables declarative, bidirectional scroll position tracking and programmatic scrolling.

swift
@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) }}

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 [blocked] for full ScrollPosition, paged reveal, zoom/crop conflict, and iOS 26 edge-effect patterns.

Form and Controls

Form

Use Form for structured settings and input screens. Group related controls into Section blocks.

swift
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

ControlUsage
ToggleBoolean preferences
PickerDiscrete choices; .segmented for 2-4 options
SliderNumeric ranges with visible value label
DatePickerDate/time selection
TextFieldText 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.

Avoid .pickerStyle(.segmented) for large sets; use menu or inline styles. Don't hide labels for sliders; always show context.

See references/form.md [blocked] for full form examples.

Searchable

Add native search UI with .searchable. Use .searchScopes for multiple modes and .task(id:) for debounced async results.

swift
@MainActorstruct 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.

swift
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

  1. Placing GeometryReader inside lazy containers defeats lazy loading; use .onGeometryChange when dimensions are needed.
  2. Array indices make unstable ForEach IDs and produce incorrect diffing.
  3. Same-axis nested scroll views create gesture conflicts.
  4. Heavy custom or expanding List rows belong in ScrollView + LazyVStack.
  5. Large option sets should use menu or inline picker styles, not .segmented.
  6. Omit stack/grid spacing: for platform-adaptive defaults unless a specific gap is intentional.
  7. Drive a scroll reveal from one normalized progress value, not parallel booleans or a duplicate drag gesture.
  8. Keep per-frame scroll geometry local and avoid changing the geometry used to calculate progress.

Review Checklist

  • LazyVStack/LazyHStack used for large or dynamic collections
  • Stable Identifiable IDs on all ForEach items (not array indices)
  • No GeometryReader inside lazy containers
  • List style matches context (.plain for feeds, .insetGrouped for settings)
  • Form used for structured input screens (not custom stacks)
  • .searchable debounces input with .task(id:)
  • .refreshable added where data source supports pull-to-refresh
  • Overlays use transitions and auto-dismiss timers
  • .contentShape(Rectangle()) on tappable rows
  • @FocusState manages keyboard focus in forms
  • Stack/grid spacing: omitted unless a specific value is required
  • Scroll-driven reveals use one normalized progress value and keep geometry updates in a narrow subtree
  • Conflicting zoom/crop interactions disable scrolling, and discrete visibility effects do not drive continuous animation

References

  • Grid patterns: references/grids.md [blocked]
  • List and section patterns: references/list.md [blocked]
  • ScrollView and lazy stacks: references/scrollview.md [blocked]
  • Form patterns: references/form.md [blocked]
  • Architecture and state management: see swiftui-patterns skill
  • Navigation patterns: see swiftui-navigation skill

來源與署名

來源:dpearson2699/swift-ios-skills位於skills/swiftui-layout-components提交8d90fd1

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 dpearson2699/swift-ios-skills 的技能

Widgetkit

dpearson2699

指導實作、審查與改進 iOS、iPadOS、watchOS 與 CarPlay 上的 WidgetKit 小工具與控制項。

Software Development1.1K2 個月前更新

Weatherkit

dpearson2699

指導 iOS 開發者使用 WeatherService 取得 WeatherKit 預報、警報與署名資訊。

Software Development1.1K2 個月前更新

Vision Framework

dpearson2699

Implement computer vision features including text recognition (OCR), face detection, barcode scanning, image segmentation, object tracking, and document scanning in iOS apps. Covers both the modern Swift-native Vision API (iOS 18+) and legacy VNRequest patterns, VisionKit DataScannerViewController for live camera scanning, and CoreMLRequest/VNCoreMLRequest for custom model inference. Use when adding OCR, barcode scanning, face detection, or custom Core ML model inference with Vision.

待分類1.1K2 個月前更新

Tipkit

dpearson2699

Implement and review Apple TipKit feature-discovery UI for iOS 17+ apps. Use when adding or auditing in-app tips, contextual help, coach marks, Tip, TipView, popoverTip, rules, events, actions, display frequency, testing overrides, reusable tip identifiers, or iOS 18+ TipGroup and CloudKit tip sync; avoid for generic SwiftUI navigation or layout outside tip presentation.

待分類1.1K2 個月前更新

Tabletopkit

dpearson2699

指導使用 TabletopKit 在 visionOS 上打造多人空間桌遊,涵蓋棋具、座位、動作與 RealityKit 算繪。

Software Development1.1K2 個月前更新

Swiftui Webkit

dpearson2699

指導在 iOS 26 及更新版本的 SwiftUI App 中使用 WebKit for SwiftUI 嵌入與控制網頁內容。

Software Development1.1K2 個月前更新