Communitygithub.com

ComeOnOliver/skillshub

參考 — 完整的 SwiftUI 自適應佈局 API 指南,涵蓋 ViewThatFits、AnyLayout、Layout 協定、onGeometryChange、GeometryReader、尺寸類別以及 iOS 26 視窗 API

skillshub 是什麼?

這份技能提供了一份全面的 SwiftUI 佈局 API 參考文件,專為構建自適應介面的開發者設計。它詳細解釋了所有關鍵的佈局工具,包括 ViewThatFits、AnyLayout、Layout 協定、onGeometryChange、GeometryReader、安全區域填充、尺寸類別以及最新的 iOS 26 視窗 API。每個 API 都配有清晰的程式碼範例、最佳實踐以及常見陷阱的說明,幫助開發者做出正確的技術決策。該技能支援 iOS 13+ 到最新的 iOS 26 版本,並針對 iOS 17+ 引入了 `.safeAreaPadding()` 等現代宣告式 API,以簡化安全區域處理。透過這份指南,開發者可以學習如何建立流暢動畫、高效幾何讀取以及真正自適應的使用者介面,從而提升 SwiftUI 應用的品質與開發效率。

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

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

SwiftUI 佈局 API 參考

全面的 SwiftUI 自適應佈局工具 API 參考。有關決策指導和反模式,請參閱 axiom-swiftui-layout 技能。

概述

本參考涵蓋用於構建自適應介面的所有 SwiftUI 佈局 API:

  • ViewThatFits — 自動變體選擇(iOS 16+)
  • AnyLayout — 型別抹消的動畫佈局切換(iOS 16+)
  • Layout 協定 — 自訂佈局演算法(iOS 16+)
  • onGeometryChange — 高效的幾何讀取(iOS 16+,向後移植)
  • GeometryReader — 佈局階段的幾何存取(iOS 13+)
  • 安全區域填充 — .safeAreaPadding() 與 .padding() 的比較(iOS 17+)
  • 尺寸類別 — 基於特徵的適應
  • iOS 26 視窗 API — 自由形式視窗、選單列、調整大小錨點

ViewThatFits

按順序評估子視圖,並顯示第一個適合可用空間的視圖。

基本用法

ViewThatFits {
    // 首選
    HStack {
        icon
        title
        Spacer()
        button
    }

    // 次選
    HStack {
        icon
        title
        button
    }

    // 備選
    VStack {
        HStack { icon; title }
        button
    }
}

使用軸向約束

// 僅考慮水平方向
ViewThatFits(in: .horizontal) {
    wideVersion
    narrowVersion
}

// 僅考慮垂直方向
ViewThatFits(in: .vertical) {
    tallVersion
    shortVersion
}

運作方式

  1. 對每個子視圖套用 fixedSize()
  2. 根據可用空間測量理想尺寸
  3. 回傳第一個適合的子視圖
  4. 如果都不適合,則回退到最後一個子視圖

限制

  • 不公開選擇了哪個變體
  • 無法在變體之間進行動畫(請改用 AnyLayout)
  • 測量所有變體(對於複雜視圖有性能考量)

AnyLayout

型別抹消的佈局容器,支援在佈局之間進行動畫過渡。

基本用法

struct AdaptiveView: View {
    @Environment(\.horizontalSizeClass) var sizeClass

    var layout: AnyLayout {
        sizeClass == .compact
            ? AnyLayout(VStackLayout(spacing: 12))
            : AnyLayout(HStackLayout(spacing: 20))
    }

    var body: some View {
        layout {
            ForEach(items) { item in
                ItemView(item: item)
            }
        }
        .animation(.default, value: sizeClass)
    }
}

可用的佈局類型

AnyLayout(HStackLayout(alignment: .top, spacing: 10))
AnyLayout(VStackLayout(alignment: .leading, spacing: 8))
AnyLayout(ZStackLayout(alignment: .center))
AnyLayout(GridLayout(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 10))

自訂條件

// 基於 Dynamic Type
@Environment(\.dynamicTypeSize) var typeSize

var layout: AnyLayout {
    typeSize.isAccessibilitySize
        ? AnyLayout(VStackLayout())
        : AnyLayout(HStackLayout())
}

// 基於幾何
@State private var isWide = true

var layout: AnyLayout {
    isWide
        ? AnyLayout(HStackLayout())
        : AnyLayout(VStackLayout())
}

為何使用它而非條件視圖

// ❌ 失去視圖身份,無法動畫
if isCompact {
    VStack { content }
} else {
    HStack { content }
}

// ✅ 保留身份,平滑動畫
let layout = isCompact ? AnyLayout(VStackLayout()) : AnyLayout(HStackLayout())
layout { content }

Layout 協定

建立自訂佈局容器,完全控制定位。

基本自訂佈局

struct FlowLayout: Layout {
    var spacing: CGFloat = 8

    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
        let sizes = subviews.map { $0.sizeThatFits(.unspecified) }
        return calculateSize(for: sizes, in: proposal.width ?? .infinity)
    }

    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
        var point = bounds.origin
        var lineHeight: CGFloat = 0

        for subview in subviews {
            let size = subview.sizeThatFits(.unspecified)

            if point.x + size.width > bounds.maxX {
                point.x = bounds.origin.x
                point.y += lineHeight + spacing
                lineHeight = 0
            }

            subview.place(at: point, proposal: .unspecified)
            point.x += size.width + spacing
            lineHeight = max(lineHeight, size.height)
        }
    }
}

// 用法
FlowLayout(spacing: 12) {
    ForEach(tags) { tag in
        TagView(tag: tag)
    }
}

使用快取

struct CachedLayout: Layout {
    struct CacheData {
        var sizes: [CGSize] = []
    }

    func makeCache(subviews: Subviews) -> CacheData {
        CacheData(sizes: subviews.map { $0.sizeThatFits(.unspecified) })
    }

    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout CacheData) -> CGSize {
        // 使用 cache.sizes 而非重新測量
    }
}

佈局值

// 定義自訂佈局值
struct Rank: LayoutValueKey {
    static let defaultValue: Int = 0
}

extension View {
    func rank(_ value: Int) -> some View {
        layoutValue(key: Rank.self, value: value)
    }
}

// 在佈局中讀取
func placeSubviews(...) {
    let sorted = subviews.sorted { $0[Rank.self] < $1[Rank.self] }
}

onGeometryChange

高效的幾何讀取,無佈局副作用。向後移植至 iOS 16+。

基本用法

@State private var size: CGSize = .zero

var body: some View {
    content
        .onGeometryChange(for: CGSize.self) { proxy in
            proxy.size
        } action: { newSize in
            size = newSize
        }
}

讀取特定值

// 僅寬度
.onGeometryChange(for: CGFloat.self) { proxy in
    proxy.size.width
} action: { width in
    columnCount = max(1, Int(width / 150))
}

// 在座標空間中的框架
.onGeometryChange(for: CGRect.self) { proxy in
    proxy.frame(in: .global)
} action: { frame in
    globalFrame = frame
}

// 長寬比
.onGeometryChange(for: Bool.self) { proxy in
    proxy.size.width > proxy.size.height
} action: { isWide in
    self.isWide = isWide
}

座標空間

// 命名座標空間
ScrollView {
    content
        .onGeometryChange(for: CGFloat.self) { proxy in
            proxy.frame(in: .named("scroll")).minY
        } action: { offset in
            scrollOffset = offset
        }
}
.coordinateSpace(name: "scroll")

與 GeometryReader 的比較

方面onGeometryChangeGeometryReader
佈局影響無貪婪(填滿空間)
評估時機佈局之後佈局期間
使用場景副作用佈局計算
iOS 版本16+(已向後移植)13+

GeometryReader

在佈局階段提供幾何資訊。由於貪婪尺寸調整,請謹慎使用。

基本用法(受約束)

// ✅ 始終約束 GeometryReader
GeometryReader { proxy in
    let width = proxy.size.width
    HStack(spacing: 0) {
        Rectangle().frame(width: width * 0.3)
        Rectangle().frame(width: width * 0.7)
    }
}
.frame(height: 100)  // 必需的約束

GeometryProxy 屬性

GeometryReader { proxy in
    // 容器大小
    let size = proxy.size  // CGSize

    // 安全區域邊距
    let insets = proxy.safeAreaInsets  // EdgeInsets

    // 在座標空間中的框架
    let globalFrame = proxy.frame(in: .global)
    let localFrame = proxy.frame(in: .local)
    let namedFrame = proxy.frame(in: .named("container"))
}

常見模式

// 比例大小調整
GeometryReader { geo in
    VStack {
        header.frame(height: geo.size.height * 0.2)
        content.frame(height: geo.size.height * 0.8)
    }
}

// 使用偏移量居中
GeometryReader { geo in
    content
        .position(x: geo.size.width / 2, y: geo.size.height / 2)
}

避免常見錯誤

// ❌ 在 VStack 中未受約束
VStack {
    GeometryReader { ... }  // 佔用所有空間
    Button("Next") { }       // 不可見
}

// ✅ 受約束
VStack {
    GeometryReader { ... }
        .frame(height: 200)
    Button("Next") { }
}

// ❌ 導致佈局循環
GeometryReader { geo in
    content
        .frame(width: geo.size.width)  // 可能導致無限循環
}

安全區域填充

SwiftUI 提供了兩種主要方法來處理內容周圍的間距:.padding() 和 .safeAreaPadding()。了解何時使用哪一種對於在有安全區域(瀏海、動態島、主畫面指示器)的裝置上進行正確佈局至關重要。

關鍵差異

// ❌ 錯誤 - 忽略安全區域,內容碰到瀏海/主畫面指示器
ScrollView {
    content
}
.padding(.horizontal, 20)

// ✅ 正確 - 尊重安全區域,在其之外添加內邊距
ScrollView {
    content
}
.safeAreaPadding(.horizontal, 20)

關鍵見解:.padding() 從視圖邊緣添加固定間距。.safeAreaPadding() 在安全區域邊距之外添加間距。

何時使用

使用 .padding() 時機

  • 在容器內的兄弟視圖之間添加間距
  • 建立應在各處一致的內部間距
  • 與已尊重安全區域的視圖(如 List、Form)一起使用
  • 在 macOS 上添加裝飾性間距(無安全區域問題)
VStack(spacing: 0) {
    header
        .padding(.horizontal, 16)  // ✅ 內部間距

    Divider()

    content
        .padding(.horizontal, 16)  // ✅ 內部間距
}

使用 .safeAreaPadding() 時機(iOS 17+)

  • 為延伸到螢幕邊緣的全寬內容添加邊距
  • 實現具有適當邊距的邊到邊滾動
  • 創建需要感知安全區域的自訂容器
  • 使用 Liquid Glass 或全螢幕素材
// ✅ 具有自訂內邊距的邊到邊列表
List(items) { item in
    ItemRow(item)
}
.listStyle(.plain)
.safeAreaPadding(.horizontal, 20)  // 在安全區域外添加 20pt

// ✅ 具有適當邊距的全螢幕內容
ZStack {
    Color.blue.ignoresSafeArea()

    VStack {
        content
    }
    .safeAreaPadding(.all, 16)  // 尊重瀏海、主畫面指示器
}

平台可用性

iOS 17+、iPadOS 17+、macOS 14+、visionOS 1.0+

對於更早的 iOS 版本,請使用手動安全區域處理:

// iOS 13-16 備用方案
GeometryReader { geo in
    content
        .padding(.horizontal, 20 + geo.safeAreaInsets.leading)
}

或條件式編譯:

if #available(iOS 17, *) {
    content.safeAreaPadding(.horizontal, 20)
} else {
    content.padding(.horizontal, 20)
        .padding(.leading, safeAreaInsets.leading)
}

邊緣特定用法

// 僅頂部(狀態列/瀏海下方)
.safeAreaPadding(.top, 8)

// 僅底部(主畫面指示器上方)
.safeAreaPadding(.bottom, 16)

// 水平(安全區域的左/右)
.safeAreaPadding(.horizontal, 20)

// 所有邊緣
.safeAreaPadding(.all, 16)

// 個別邊緣
.safeAreaPadding(EdgeInsets(top: 8, leading: 20, bottom: 16, trailing: 20))

常見模式

邊到邊 ScrollView

ScrollView {
    LazyVStack(spacing: 12) {
        ForEach(items) { item in
            ItemCard(item)
        }
    }
}
.safeAreaPadding(.horizontal, 16)  // 來自邊緣 + 安全區域的內容邊距
.safeAreaPadding(.vertical, 8)

具有安全內容的全螢幕背景

ZStack {
    // 背景延伸到邊到邊
    LinearGradient(...)
        .ignoresSafeArea()

    // 內容尊重安全區域 + 自訂內邊距
    VStack {
        header
        Spacer()
        content
        Spacer()
        footer
    }
    .safeAreaPadding(.all, 20)
}

巢狀內邊距(組合方法)

// 外層:裝置邊距的安全區域內邊距
VStack(spacing: 0) {
    content
}
.safeAreaPadding(.horizontal, 16)  // 安全區域之外

// 內層:內部間距的常規內邊距
VStack {
    Text("Title")
        .padding(.bottom, 8)  // 內部間距
    Text("Subtitle")
}

決策樹

您的內容是否延伸到螢幕邊緣?
├─ 是 → 使用 .safeAreaPadding()
│   ├─ 它是可滾動的嗎? → .safeAreaPadding(.horizontal/.vertical)
│   └─ 它是全螢幕的嗎? → .safeAreaPadding(.all)
│
└─ 否(包含在安全的容器內,如 List/Form)
    └─ 對於內部間距,使用 .padding()

視覺除錯

// 可視化安全區域內邊距(iOS 17+)
content
    .safeAreaPadding(.horizontal, 20)
    .background(.red.opacity(0.2))  // 顯示內邊距區域
    .border(.blue)  // 顯示內容邊界

從手動安全區域處理遷移

// ❌ 舊方法:手動計算(iOS 13-16)
GeometryReader { geo in
    content
        .padding(.top, geo.safeAreaInsets.top + 16)
        .padding(.bottom, geo.safeAreaInsets.bottom + 16)
        .padding(.horizontal, 20)
}

// ✅ 新方法:.safeAreaPadding() (iOS 17+)
content
    .safeAreaPadding(.vertical, 16)
    .safeAreaPadding(.horizontal, 20)

相關 API

.safeAreaInset(edge:) - 添加縮小安全區域的持續性內容:

ScrollView {
    content
}
.safeAreaInset(edge: .bottom) {
    // 這會縮小安全區域,內容在其下方滾動
    toolbarButtons
        .padding()
        .background(.ultraThinMaterial)
}

.ignoresSafeArea() - 完全退出安全區域:

Color.blue
    .ignoresSafeArea()  // 延伸到絕對螢幕邊緣

為何重要

iOS 17 之前:開發人員必須使用 GeometryReader 手動計算安全區域邊距,導致:

  • 囉嗦的程式碼
  • 效能開銷(GeometryReader 強制進行額外的佈局傳遞)
  • 容易出錯(忘記檢查所有邊緣)

iOS 17+:.safeAreaPadding() 提供:

  • 宣告式 API(符合 SwiftUI 哲學)
  • 自動安全區域感知
  • 更好的效能(無額外佈局傳遞)
  • 型別安全的邊緣指定

實際影響

…

[因翻譯而截斷]

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

相關技能