Communitygithub.com

ComeOnOliver/skillshub

在佈局需要適應不同螢幕大小、iPad 多工處理或 iOS 26 自由形式視窗時使用 — 包含 ViewThatFits 與 AnyLayout 與 onGeometryChange 的決策樹、尺寸類別限制,以及防止基於裝置的佈局錯誤的反模式。

skillshub 是什麼?

此技能為一個規範性的 SwiftUI 適應性佈局指南,旨在強制開發者根據可用空間(而非裝置假設)來建構佈局。它提供了一個清晰的決策樹來選擇正確的工具,例如 ViewThatFits、AnyLayout、onGeometryChange 和 Layout 協定,並詳細解釋了何時以及為何使用它們。技能深入探討了 iOS 26 中自由形式視窗的重大變革,包括 UIRequiresFullScreen 的棄用和 NavigationSplitView 的自動適應。它還透過一份真實數據表,揭示了 iPad 上尺寸類別(horizontalSizeClass)在分割視圖中的侷限性(例如,在 33% 分割視圖之前可能保持 .regular)。此外,它明確指出了常見的反模式,例如使用 UIDevice.current.orientation、UIScreen.main.bounds 或硬編碼的裝置檢查,並提供了使用 onGeometryChange 的基於空間的修正方案。這個技能非常適合在 Cursor、Claude Code 或 Codex 等 AI 編碼代理中使用,能協助開發者撰寫更具前瞻性、更穩健的 SwiftUI 佈局程式碼。

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

在你喜歡的 AI 中提問

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

說明文件

SwiftUI 適應性佈局

概述

這是一個紀律強化的技能,用於建構能夠回應可用空間而非裝置假設的佈局。涵蓋工具選擇、尺寸類別限制、iOS 26 自由形式視窗以及常見的反模式。

核心原則: 你的佈局應該在 Apple 明天推出新裝置時,或是 iPadOS 明年新增新模式時,都能正常運作。回應你的容器,而不是你對裝置的假設。

何時使用此技能

  • 「如何讓這個佈局在 iPad 和 iPhone 上都正常運作?」
  • 「我應該使用 GeometryReader 還是 ViewThatFits?」
  • 「我的佈局在分割顯示 / 舞台管理器(Stage Manager)下會壞掉」
  • 「尺寸類別沒有提供我需要的資訊」
  • 「設計師想要直向與橫向有不同的佈局」
  • 「為 iOS 26 視窗調整大小功能做準備」

決策樹

「我需要我的佈局適應...」
│
├─ 到可用空間 (由容器驅動)
│   │
│   ├─ 「挑選最合適的變體」
│   │   → ViewThatFits
│   │
│   ├─ 「在 H↔V 之間切換並帶有動畫」
│   │   → AnyLayout + 條件判斷
│   │
│   ├─ 「讀取尺寸進行計算」
│   │   → onGeometryChange (iOS 16+)
│   │
│   └─ 「自訂佈局演算法」
│       → Layout 協定
│
├─ 到平台特性
│   │
│   ├─ 「緊湊 vs 常規寬度」
│   │   → horizontalSizeClass (⚠️ iPad 限制)
│   │
│   ├─ 「輔助使用文字大小」
│   │   → dynamicTypeSize.isAccessibilitySize
│   │
│   └─ 「平台差異」
│       → #if os() / 環境變數
│
└─ 到視窗形狀 (長寬比)
    │
    ├─ 「直向 vs 橫向的語意」
    │   → Geometry + 自訂閾值
    │
    ├─ 「自動顯示/隱藏欄位」
    │   → NavigationSplitView (iOS 26 自動化)
    │
    └─ 「視窗生命週期」
        → @Environment(\.scenePhase)

工具選擇

快速決策

你需要一個計算出來的值(寬度、高度)嗎?
├─ 是 → onGeometryChange
└─ 否 → 你需要動畫過渡效果嗎?
         ├─ 是 → AnyLayout + 條件判斷
         └─ 否 → ViewThatFits

何時使用哪個工具

我需要...使用這個不要用這個
在 2-3 個佈局變體間選擇ViewThatFitsif size > X
在 H↔V 動畫切換AnyLayout條件式 HStack/VStack
讀取容器尺寸onGeometryChangeGeometryReader
適應輔助使用文字dynamicTypeSize固定的斷點
檢測緊湊寬度horizontalSizeClassUIDevice.idiom
檢測 iPad 上的窄視窗Geometry + 閾值僅使用 Size class
顯示/隱藏側邊欄NavigationSplitView手動欄位邏輯
自訂佈局演算法Layout 協定巢狀 GeometryReader

模式 1:ViewThatFits

使用時機: 當你有 2-3 個佈局變體,並希望 SwiftUI 選擇第一個能放進去的。

ViewThatFits {
    // 首選:水平
    HStack {
        Image(systemName: "star")
        Text("Favorite")
        Spacer()
        Button("Add") { }
    }

    // 備用:垂直
    VStack {
        HStack {
            Image(systemName: "star")
            Text("Favorite")
        }
        Button("Add") { }
    }
}

限制: ViewThatFits 不會公開被選擇的是哪個變體。如果你需要這個狀態給其他視圖使用,請改用 AnyLayout。


模式 2:AnyLayout 用於動畫切換

使用時機: 當你需要在佈局之間進行動畫過渡,或者需要知道當前的佈局狀態。

struct AdaptiveStack<Content: View>: View {
    @Environment(\.horizontalSizeClass) var sizeClass

    let content: Content

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

    var body: some View {
        layout {
            content
        }
        .animation(.default, value: sizeClass)
    }
}

用於動態類型 (Dynamic Type):

@Environment(\.dynamicTypeSize) var dynamicTypeSize

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

模式 3:onGeometryChange (幾何計算的首選)

使用時機: 當你需要實際尺寸來進行計算。是 GeometryReader 的首選替代方案。

struct ResponsiveGrid: View {
    @State private var columnCount = 2

    var body: some View {
        LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: columnCount)) {
            ForEach(items) { item in
                ItemView(item: item)
            }
        }
        .onGeometryChange(for: Int.self) { proxy in
            max(1, Int(proxy.size.width / 150))
        } action: { newCount in
            columnCount = newCount
        }
    }
}

用於長寬比檢測(iPad「方向」):

struct WindowShapeReader: View {
    @State private var isWide = true

    var body: some View {
        content
            .onGeometryChange(for: Bool.self) { proxy in
                proxy.size.width > proxy.size.height * 1.2
            } action: { newValue in
                isWide = newValue
            }
    }
}

模式 4:GeometryReader (必要時使用)

使用時機: 當你需要幾何資訊,並且 (a) 你的目標是 iOS 15 或更早版本,或者 (b) 需要在佈局階段(而非僅作為副作用)取得幾何資料時。

// ✅ 正確:受限的 GeometryReader
VStack {
    GeometryReader { geo in
        Text("Width: \(geo.size.width)")
    }
    .frame(height: 44)  // 必須限制尺寸!

    Button("Next") { }
}

// ❌ 錯誤:不受限(貪婪)
VStack {
    GeometryReader { geo in
        Text("Width: \(geo.size.width)")
    }
    // 佔據所有可用空間,擠壓兄弟視圖
    Button("Next") { }
}

尺寸類別真實數據表 (iPad)

配置水平垂直
全螢幕直向.regular.regular
全螢幕橫向.regular.regular
70% 分割視圖.regular.regular
50% 分割視圖.regular.regular
33% 分割視圖.compact.regular
Slide Over.compact.regular
使用鍵盤時(不變)(不變)

關鍵見解: iPad 的 Size Class 只有在約 33% 寬度或 Slide Over 時才會變成 .compact。如需更精細的控制,請使用幾何計算。


iOS 26 自由形式視窗

改變了什麼

iOS 26 之前iOS 26+
固定的分割視圖尺寸自由拖動調整大小
允許使用 UIRequiresFullScreen已棄用
iPad 上無選單列透過 .commands 提供選單列
手動欄位可見性NavigationSplitView 自動適應

Apple 的準則

「調整應用程式大小不應永久改變其佈局。在可能的情況下,應伺機恢復到起始狀態。」

翻譯: 不要根據視窗大小儲存佈局狀態。當視窗恢復到原始尺寸時,佈局也應恢復。

NavigationSplitView 自動適應

// iOS 26:欄位會自動顯示/隱藏
NavigationSplitView {
    Sidebar()
} content: {
    ContentList()
} detail: {
    DetailView()
}
// 不需要手動管理 columnVisibility

遷移檢查清單

  • 從 Info.plist 中移除 UIRequiresFullScreen
  • 在任意視窗尺寸(不僅是 33/50/66%)下測試
  • 確認佈局在調整大小後不會「卡住」
  • 為常用操作添加選單列指令
  • 測試視窗控制元件不會與工具列項目重疊

反模式

❌ 裝置方向觀察者

// ❌ 錯誤:回報的是裝置,不是視窗
NotificationCenter.default.addObserver(
    forName: UIDevice.orientationDidChangeNotification, ...
)

let orientation = UIDevice.current.orientation
if orientation.isLandscape { ... }

為什麼會失敗: 回報的是物理裝置的方向,而非視窗的形狀。在分割視圖、舞台管理器 (Stage Manager)、iOS 26 中都是錯誤的。

修正方法: 使用 onGeometryChange 讀取實際的視窗尺寸。

❌ 螢幕邊界

// ❌ 錯誤:回傳的是全螢幕,不是你的視窗
let width = UIScreen.main.bounds.width
if width > 700 { useWideLayout() }

為什麼會失敗: 在多工處理中,你的應用程式可能只擁有螢幕的 40%。

修正方法: 讀取你視圖的實際容器尺寸。

❌ 裝置型號檢查

// ❌ 錯誤:在新裝置上會失效,在多工處理中錯誤
if UIDevice.current.userInterfaceIdiom == .pad {
    useWideLayout()
}

為什麼會失敗: 處於 1/3 分割視圖下的 iPad 會比橫向的 iPhone 14 Pro Max 更窄。

修正方法: 回應可用空間,而不是裝置身份。

❌ 不受限的 GeometryReader

// ❌ 錯誤:GeometryReader 是貪婪的
VStack {
    GeometryReader { geo in
        Text("Size: \(geo.size)")
    }
    Button("Next") { }  // 被擠壓
}

修正方法: 使用 .frame() 限制大小,或改用 onGeometryChange。

❌ 將 Size Class 作為方向代理

// ❌ 錯誤:iPad 在兩種方向下都是 .regular
var isLandscape: Bool {
    horizontalSizeClass == .regular  // 在 iPad 上永遠為 true!
}

修正方法: 如果你需要長寬比,請根據實際的幾何數據進行計算。


壓力場景

「設計師想要 iPhone 專屬的佈局」

誘惑: if UIDevice.current.userInterfaceIdiom == .phone

回應: 「我會將這些實作為『緊湊』和『常規』佈局,根據可用空間進行切換。當 iPad 視窗變窄時,iPhone 佈局會自動顯示。這能讓我們為未來支援舞台管理器 (Stage Manager) 和 iOS 26 做好準備。」

「直接用 GeometryReader 就好,沒問題的」

誘惑: 將所有東西包在 GeometryReader 裡。

回應: 「GeometryReader 有已知的佈局副作用——它會貪婪地擴張。onGeometryChange 可以讀取相同的數據,但不會影響佈局。它向後相容至 iOS 16。」

「尺寸類別以前可以運作」

誘惑: 強制所有事情都透過 Size Class 來處理。

回應: 「尺寸類別是粗略的。iPad 在兩種方向下都是 .regular。我會將 Size Class 用於廣泛的分類,並使用幾何數據進行精確的閾值判斷。」

「我們不支援 iPad 多工處理」

誘惑: UIRequiresFullScreen = true

回應: 「Apple 已在 iOS 26 中棄用了僅全螢幕模式。即使沒有主動支援分割視圖,應用程式在調整大小時也不能崩潰。基於空間的佈局成本相同。」


資源

WWDC:2025-208, 2024-10074, 2022-10056

相關技能:axiom-swiftui-layout-ref, axiom-swiftui-debugging, axiom-liquid-glass

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

相關技能