Communitygithub.com

ComeOnOliver/skillshub

参考——完整的 SwiftUI 自适应布局 API 指南,涵盖 ViewThatFits、AnyLayout、Layout 协议、onGeometryChange、GeometryReader、Size Classes 和 iOS 26 窗口 API

skillshub 是什么?

这是一个全面的 SwiftUI 自适应布局 API 参考指南,旨在帮助开发者构建适用于 iOS、iPadOS 和 macOS 的自适应界面。该技能覆盖了关键的布局技术:ViewThatFits 用于自动子视图选择,AnyLayout 支持类型擦除的动画布局切换,Layout 协议允许自定义布局算法,onGeometryChange 提供高效的几何属性读取(向下兼容至 iOS 16+),以及 GeometryReader 在布局阶段提供几何信息。此外,还详细对比了 safeAreaPadding() 与 padding() 的使用场景,并涵盖了 Size Classes 和 iOS 26 窗口 API。每个 API 都配有清晰的代码示例、使用建议和常见陷阱分析,是 SwiftUI 开发者构建响应式界面的必备参考。支持的平台包括 iOS 16+、iPadOS 16+、macOS 14+ 以及 visionOS。

兼容平台~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+)
  • Size Classes — 基于 Trait 的适配
  • 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))
}

// 在特定坐标空间中的 frame
.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

    // 在坐标空间中的 frame
    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()。了解何时使用哪种方法对于在具有安全区域(刘海屏、灵动岛、Home Indicator)的设备上正确布局至关重要。

关键区别

// ❌ 错误 - 忽略安全区域,内容会碰到刘海屏/Home Indicator
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)  // 尊重刘海屏、Home Indicator
}

平台可用性

iOS 17+, iPadOS 17+, macOS 14+, axiom-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)

// 仅底部(Home Indicator 上方)
.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

相关技能