Communitygithub.com

ComeOnOliver/skillshub

当布局需要适应不同的屏幕尺寸、iPad 多任务处理或 iOS 26 自由窗口时使用——涵盖 ViewThatFits 与 AnyLayout 与 onGeometryChange 的决策树、尺寸类限制以及防止基于设备的布局错误的反模式。

skillshub 是什么?

该技能专门针对 SwiftUI 自适应布局设计,旨在帮助开发者构建真正响应可用空间而非设备假设的布局。它提供了一个清晰的决策树,指导开发者根据需求(如选择最佳布局变体、动画切换 H/V 布局、读取容器尺寸或实现自定义布局算法)选择合适的工具,如 ViewThatFits、AnyLayout、onGeometryChange 和 Layout 协议。技能深入揭示了 iOS 26 中自由窗口和多任务处理带来的新挑战,并通过详实的示例代码展示了如何在 iPad 的分屏、Slide Over 以及未来设备的窗口尺寸变化下,确保布局正确响应。此外,该技能还列举了常见的反模式(如基于设备方向或屏幕边界进行布局决策),并提供了针对这些陷阱的实用修复方法,是实现健壮、面向未来布局的必备参考。该技能适用于 Claude Code、Cursor、Codex 等主流 AI 编码代理,并兼容所有支持 SwiftUI 的 Apple 平台。

兼容平台~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 自由窗口以及常见的反模式。

核心原则: 无论苹果明天发布新设备,还是 iPadOS 明年增加新的多任务模式,你的布局都应能正常工作。响应你的容器,而不是你对设备的假设。

何时使用此技能

  • “如何让这个布局在 iPad 和 iPhone 上都能正常工作?”
  • “我应该使用 GeometryReader 还是 ViewThatFits?”
  • “我的布局在分屏 / 台前调度下会崩溃”
  • “尺寸类无法满足我的需求”
  • “设计师希望竖屏和横屏有不同的布局”
  • “为 iOS 26 窗口大小调整做准备”

决策树

“我需要我的布局适应...”
│
├─ 可用空间(容器驱动)
│   │
│   ├─ “选择最合适的变体”
│   │   → ViewThatFits
│   │
│   ├─ “在 H↔V 之间动画切换”
│   │   → AnyLayout + 条件判断
│   │
│   ├─ “读取尺寸进行计算”
│   │   → onGeometryChange (iOS 16+)
│   │
│   └─ “自定义布局算法”
│       → Layout 协议
│
├─ 平台特征
│   │
│   ├─ “紧凑 vs 常规宽度”
│   │   → horizontalSizeClass (⚠️ iPad 限制)
│   │
│   ├─ “辅助功能文本大小”
│   │   → dynamicTypeSize.isAccessibilitySize
│   │
│   └─ “平台差异”
│       → #if os() / Environment
│
└─ 窗口形状(宽高比)
    │
    ├─ “横屏 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 + 阈值仅尺寸类
显示/隐藏侧边栏NavigationSplitView手动列逻辑
自定义布局算法Layout 协议嵌套的 GeometryReader

模式 1:ViewThatFits

何时使用: 你有 2-3 种布局变体,并希望 SwiftUI 选择第一个适合的。

ViewThatFits {
    // 首选:水平布局
    HStack {
        Image(systemName: "star")
        Text("收藏")
        Spacer()
        Button("添加") { }
    }

    // 备选:垂直布局
    VStack {
        HStack {
            Image(systemName: "star")
            Text("收藏")
        }
        Button("添加") { }
    }
}

限制: 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)
    }
}

对于动态类型:

@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(必要时使用)

何时使用: 你需要几何信息,并且运行在 iOS 15 或更早版本上,或者在布局阶段(不仅仅是作为副作用)需要几何信息。

// ✅ 正确:受约束的 GeometryReader
VStack {
    GeometryReader { geo in
        Text("宽度: \(geo.size.width)")
    }
    .frame(height: 44)  // 必须约束高度!

    Button("下一步") { }
}

// ❌ 错误:未受约束(贪婪)
VStack {
    GeometryReader { geo in
        Text("宽度: \(geo.size.width)")
    }
    // 占用所有可用空间,压扁兄弟视图
    Button("下一步") { }
}

尺寸类真值表(iPad)

配置水平方向垂直方向
全屏竖屏.regular.regular
全屏横屏.regular.regular
70% 分屏.regular.regular
50% 分屏.regular.regular
33% 分屏.compact.regular
Slide Over.compact.regular
带键盘(不变)(不变)

关键见解: 尺寸类仅在 iPad 宽度约为 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 { ... }

为什么失败: 报告的是物理设备方向,而不是窗口形状。在分屏、台前调度、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("尺寸: \(geo.size)")
    }
    Button("下一步") { }  // 被压扁
}

修复: 使用 .frame() 进行约束,或者改用 onGeometryChange。

❌ 将尺寸类作为方向代理

// ❌ 错误:iPad 在两个方向都是 .regular
var isLandscape: Bool {
    horizontalSizeClass == .regular  // 在 iPad 上始终为 true!
}

修复: 如果需要宽高比,请根据实际几何信息计算。


压力场景

“设计师想要 iPhone 特定的布局”

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

回应: “我会将这些实现为‘紧凑’和‘常规’布局,根据可用空间进行切换。当窗口较窄时,iPhone 布局也会出现在 iPad 上。这为我们以后支持台前调度和 iOS 26 提供了保障。”

“就用 GeometryReader 吧,没问题”

诱惑: 把所有东西都包在 GeometryReader 里。

回应: “GeometryReader 有已知的布局副作用——它会贪婪地扩展。onGeometryChange 读取相同的数据但不会影响布局。它向后兼容到 iOS 16。”

“尺寸类以前工作得很好”

诱惑: 强制一切通过尺寸类。

回应: “尺寸类是粗粒度的。iPad 在两个方向上都是 .regular。我会使用尺寸类来处理大类,对于精确阈值则使用几何信息。”

“我们不支持 iPad 多任务”

诱惑: UIRequiresFullScreen = true

回应: “苹果在 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

相关技能