Communitygithub.com

ComeOnOliver/skillshub

SwiftUI 容器参考——栈、网格、大纲和滚动增强,涵盖 iOS 14 至 iOS 26。

skillshub 是什么?

该技能是一个全面的 SwiftUI 容器组件参考指南,覆盖从 iOS 14 到 iOS 26 的版本。它详细讲解了所有主要的容器视图,包括基本栈(VStack、HStack、ZStack)、惰性栈(LazyVStack、LazyHStack)、网格(Grid、LazyVGrid、LazyHGrid)以及大纲组件(List、OutlineGroup、DisclosureGroup)。除了基础用法,还提供了丰富的性能优化建议,例如惰性加载策略、缓存 `GridItem` 数组以及 iOS 26 中的重大性能提升。此外,技能深入介绍了 iOS 17+ 引入的滚动增强功能,包括 `containerRelativeFrame`、`scrollTargetLayout`、`scrollPosition`、`scrollTransition`,以及 iOS 18+ 的 `onScrollGeometryChange` 和 `onScrollVisibilityChange`。它适用于任何 SwiftUI 项目,帮助开发者快速选择合适的容器组件并实现高效、流畅的界面。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/CharlesWiltgen/Axiom/axiom-swiftui-containers-ref

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

SwiftUI 容器参考

栈、网格、大纲和滚动增强。iOS 14 至 iOS 26。

来源:WWDC 2020-10031、2022-10056、2023-10148、2024-10144、2025-256

快速决策

使用场景容器iOS
固定视图垂直/水平VStack / HStack13+
重叠视图ZStack13+
大型可滚动列表LazyVStack / LazyHStack14+
多列网格LazyVGrid14+
多行网格(水平)LazyHGrid14+
静态网格,精确对齐Grid16+
分层数据(树)List 使用 children:14+
自定义层级OutlineGroup14+
显示/隐藏内容DisclosureGroup14+

第一部分:栈

VStack、HStack、ZStack

VStack(alignment: .leading, spacing: 12) {
    Text("标题")
    Text("副标题")
}

HStack(alignment: .top, spacing: 8) {
    Image(systemName: "star")
    Text("评分")
}

ZStack(alignment: .bottomTrailing) {
    Image("photo")
    Badge()
}

ZStack 对齐方式:.center(默认)、.top、.bottom、.leading、.trailing、.topLeading、.topTrailing、.bottomLeading、.bottomTrailing

Spacer

HStack {
    Text("左侧")
    Spacer()
    Text("右侧")
}

Spacer(minLength: 20)  // 最小尺寸

LazyVStack、LazyHStack(iOS 14+)

仅在视图可见时渲染子视图。请配合 ScrollView 使用。

ScrollView {
    LazyVStack(spacing: 0) {
        ForEach(items) { item in
            ItemRow(item: item)
        }
    }
}

固定的分区标题

ScrollView {
    LazyVStack(pinnedViews: [.sectionHeaders]) {
        ForEach(sections) { section in
            Section(header: SectionHeader(section)) {
                ForEach(section.items) { item in
                    ItemRow(item: item)
                }
            }
        }
    }
}

第二部分:网格

Grid(iOS 16+)

非惰性网格,支持精确对齐。一次性加载所有视图。

Grid(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 10) {
    GridRow {
        Text("姓名")
        TextField("输入姓名", text: $name)
    }
    GridRow {
        Text("邮箱")
        TextField("输入邮箱", text: $email)
    }
}

修饰符:

  • gridCellColumns(_:) — 跨越多个列
  • gridColumnAlignment(_:) — 覆盖列对齐
Grid {
    GridRow {
        Text("表头").gridCellColumns(2)
    }
    GridRow {
        Text("左侧")
        Text("右侧").gridColumnAlignment(.trailing)
    }
}

LazyVGrid(iOS 14+)

垂直滚动网格。定义列;行数无限制增长。

let columns = [
    GridItem(.flexible()),
    GridItem(.flexible()),
    GridItem(.flexible())
]

ScrollView {
    LazyVGrid(columns: columns, spacing: 16) {
        ForEach(items) { item in
            ItemCard(item: item)
        }
    }
}

LazyHGrid(iOS 14+)

水平滚动网格。定义行;列数无限制增长。

let rows = [GridItem(.fixed(100)), GridItem(.fixed(100))]

ScrollView(.horizontal) {
    LazyHGrid(rows: rows, spacing: 16) {
        ForEach(items) { item in
            ItemCard(item: item)
        }
    }
}

GridItem.Size

尺寸行为
.fixed(CGFloat)精确的宽度/高度
.flexible(minimum:maximum:)均匀填充空间
.adaptive(minimum:maximum:)创建尽量多的项目
// 自适应:列数响应式
let columns = [GridItem(.adaptive(minimum: 150))]

第三部分:大纲

带分层数据的 List(iOS 14+)

struct FileItem: Identifiable {
    let id = UUID()
    var name: String
    var children: [FileItem]?  // nil 表示叶子节点
}

List(files, children: \.children) { file in
    Label(file.name, systemImage: file.children != nil ? "文件夹" : "文档")
}
.listStyle(.sidebar)

OutlineGroup(iOS 14+)

用于在 List 外部实现自定义层级布局。

List {
    ForEach(canvases) { canvas in
        Section(header: Text(canvas.name)) {
            OutlineGroup(canvas.graphics, children: \.children) { graphic in
                GraphicRow(graphic: graphic)
            }
        }
    }
}

DisclosureGroup(iOS 14+)

@State private var isExpanded = false

DisclosureGroup("高级选项", isExpanded: $isExpanded) {
    Toggle("启用功能", isOn: $feature)
    Slider(value: $intensity)
}

第四部分:常见模式

照片网格

let columns = [GridItem(.adaptive(minimum: 100), spacing: 2)]

ScrollView {
    LazyVGrid(columns: columns, spacing: 2) {
        ForEach(photos) { photo in
            AsyncImage(url: photo.thumbnailURL) { image in
                image.resizable().aspectRatio(1, contentMode: .fill)
            } placeholder: { Color.gray }
            .aspectRatio(1, contentMode: .fill)
            .clipped()
        }
    }
}

水平轮播

ScrollView(.horizontal, showsIndicators: false) {
    LazyHStack(spacing: 16) {
        ForEach(items) { item in
            CarouselCard(item: item).frame(width: 280)
        }
    }
    .padding(.horizontal)
}

文件浏览器

List(selection: $selection) {
    OutlineGroup(rootItems, children: \.children) { item in
        Label {
            Text(item.name)
        } icon: {
            Image(systemName: item.children != nil ? "folder.fill" : "doc.fill")
        }
    }
}
.listStyle(.sidebar)

第五部分:性能

何时使用惰性

尺寸可滚动?使用
1-20否VStack/HStack
1-20是在 ScrollView 中使用 VStack/HStack
20-100是LazyVStack/LazyHStack
100+是LazyVStack/LazyHStack 或 List
网格 <50否Grid
网格 50+是LazyVGrid/LazyHGrid

缓存 GridItem 数组 — 在 body 外部定义:

struct ContentView: View {
    let columns = [GridItem(.adaptive(minimum: 150))]  // ✅
    var body: some View {
        LazyVGrid(columns: columns) { ... }
    }
}

iOS 26 性能

  • 列表加载速度提升 6 倍(针对 10 万+ 项目)
  • 列表更新速度提升 16 倍
  • 滚动时丢帧减少
  • 嵌套 ScrollView 与惰性栈现在能正确延迟加载:
ScrollView(.horizontal) {
    LazyHStack {
        ForEach(photoSets) { set in
            ScrollView(.vertical) {
                LazyVStack {
                    ForEach(set.photos) { PhotoView(photo: $0) }
                }
            }
        }
    }
}

第六部分:滚动增强

containerRelativeFrame(iOS 17+)

根据滚动容器调整视图尺寸。

ScrollView(.horizontal) {
    LazyHStack {
        ForEach(cards) { card in
            CardView(card: card)
                .containerRelativeFrame(.horizontal, count: 3, span: 1, spacing: 16)
        }
    }
}

scrollTargetLayout(iOS 17+)

启用吸附效果。

ScrollView(.horizontal) {
    LazyHStack {
        ForEach(items) { ItemCard(item: $0) }
    }
    .scrollTargetLayout()
}
.scrollTargetBehavior(.viewAligned)

scrollPosition(iOS 17+)

跟踪最顶端可见项目。每个项目都需要 .id()。

@State private var position: Item.ID?

ScrollView {
    LazyVStack {
        ForEach(items) { item in
            ItemRow(item: item).id(item.id)
        }
    }
}
.scrollPosition(id: $position)

scrollTransition(iOS 17+)

.scrollTransition { content, phase in
    content
        .opacity(1 - abs(phase.value) * 0.5)
        .scaleEffect(phase.isIdentity ? 1.0 : 0.75)
}

onScrollGeometryChange(iOS 18+)

.onScrollGeometryChange(for: Bool.self) { geo in
    geo.contentOffset.y < geo.contentInsets.top
} action: { _, isTop in
    showBackButton = !isTop
}

onScrollVisibilityChange(iOS 18+)

VideoPlayer(player: player)
    .onScrollVisibilityChange(threshold: 0.2) { visible in
        visible ? player.play() : player.pause()
    }

资源

WWDC:2020-10031、2022-10056、2023-10148、2024-10144、2025-256

文档:/swiftui/lazyvstack、/swiftui/lazyvgrid、/swiftui/lazyhgrid、/swiftui/grid、/swiftui/outlinegroup、/swiftui/disclosuregroup

技能:axiom-swiftui-layout、axiom-swiftui-layout-ref、axiom-swiftui-nav、axiom-swiftui-26-ref

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相关技能