Communitygithub.com

SwiftUI 模式(ComeOnOliver/skillshub)

SwiftUI 架构模式、@Observable 状态管理、视图组合、导航、性能优化以及现代 iOS/macOS UI 最佳实践。

skillshub) 是什么?

该技能提供了在 Apple 平台上使用 SwiftUI 构建声明式、高性能用户界面的全面指南。它涵盖了现代状态管理技术,强调使用 `@Observable` 宏而非传统的 `ObservableObject` 模式,以实现更细粒度的视图更新。技能详细讲解了视图组合策略,例如提取子视图以限制状态变化时的重绘范围,以及使用 `ViewModifier` 实现可复用的样式。在导航方面,介绍了通过 `NavigationStack` 和 `NavigationPath` 进行类型安全、可编程的路由设计。性能优化部分则包括使用惰性容器、稳定标识符、避免在 `body` 中执行昂贵操作,以及通过 `Equatable` 一致性跳过不必要的重新渲染。该技能适用于 Cursor、Claude Code 等支持自定义技能的平台,为开发者提供了创建美观且高效 SwiftUI 应用的实用模板和反模式规避指南。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/affaan-m/everything-claude-code/swiftui-patterns

在你喜欢的 AI 中提问

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

文档

SwiftUI 模式

适用于 Apple 平台的现代 SwiftUI 模式,用于构建声明式、高性能的用户界面。涵盖 Observation 框架、视图组合、类型安全导航和性能优化。

何时激活

  • 构建 SwiftUI 视图并管理状态(@State、@Observable、@Binding)
  • 使用 NavigationStack 设计导航流程
  • 构建 ViewModel 结构和数据流
  • 优化列表和复杂布局的渲染性能
  • 在 SwiftUI 中处理环境值和依赖注入

状态管理

属性包装器选择

选择最适合的包装器:

包装器使用场景
@State视图本地值类型(开关、表单字段、Sheet 弹出)
@Binding对父视图 @State 的双向引用
@Observable 类 + @State拥有多属性的模型
@Observable 类(无包装器)从父视图传递的只读引用
@Bindable对 @Observable 属性的双向绑定
@Environment通过 .environment() 注入的共享依赖

@Observable ViewModel

使用 @Observable(而非 ObservableObject)——它跟踪属性级别的变化,因此 SwiftUI 只重新渲染读取了该属性的视图:

@Observable
final class ItemListViewModel {
    private(set) var items: [Item] = []
    private(set) var isLoading = false
    var searchText = ""

    private let repository: any ItemRepository

    init(repository: any ItemRepository = DefaultItemRepository()) {
        self.repository = repository
    }

    func load() async {
        isLoading = true
        defer { isLoading = false }
        items = (try? await repository.fetchAll()) ?? []
    }
}

消费 ViewModel 的视图

struct ItemListView: View {
    @State private var viewModel: ItemListViewModel

    init(viewModel: ItemListViewModel = ItemListViewModel()) {
        _viewModel = State(initialValue: viewModel)
    }

    var body: some View {
        List(viewModel.items) { item in
            ItemRow(item: item)
        }
        .searchable(text: $viewModel.searchText)
        .overlay { if viewModel.isLoading { ProgressView() } }
        .task { await viewModel.load() }
    }
}

环境注入

用 @Environment 替代 @EnvironmentObject:

// 注入
ContentView()
    .environment(authManager)

// 消费
struct ProfileView: View {
    @Environment(AuthManager.self) private var auth

    var body: some View {
        Text(auth.currentUser?.name ?? "Guest")
    }
}

视图组合

提取子视图以限制重绘

将视图分解为小型、聚焦的结构体。当状态发生变化时,只有读取该状态的子视图会重新渲染:

struct OrderView: View {
    @State private var viewModel = OrderViewModel()

    var body: some View {
        VStack {
            OrderHeader(title: viewModel.title)
            OrderItemList(items: viewModel.items)
            OrderTotal(total: viewModel.total)
        }
    }
}

用于可复用样式的 ViewModifier

struct CardModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .padding()
            .background(.regularMaterial)
            .clipShape(RoundedRectangle(cornerRadius: 12))
    }
}

extension View {
    func cardStyle() -> some View {
        modifier(CardModifier())
    }
}

导航

类型安全 NavigationStack

使用 NavigationStack 配合 NavigationPath 实现可编程、类型安全的路由:

@Observable
final class Router {
    var path = NavigationPath()

    func navigate(to destination: Destination) {
        path.append(destination)
    }

    func popToRoot() {
        path = NavigationPath()
    }
}

enum Destination: Hashable {
    case detail(Item.ID)
    case settings
    case profile(User.ID)
}

struct RootView: View {
    @State private var router = Router()

    var body: some View {
        NavigationStack(path: $router.path) {
            HomeView()
                .navigationDestination(for: Destination.self) { dest in
                    switch dest {
                    case .detail(let id): ItemDetailView(itemID: id)
                    case .settings: SettingsView()
                    case .profile(let id): ProfileView(userID: id)
                    }
                }
        }
        .environment(router)
    }
}

性能

为大型集合使用惰性容器

LazyVStack 和 LazyHStack 仅在视图可见时才创建它们:

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

稳定标识符

始终在 ForEach 中使用稳定且唯一的 ID——避免使用数组索引:

// 使用 Identifiable 协议或显式的 id
ForEach(items, id: \.stableID) { item in
    ItemRow(item: item)
}

避免在 body 中执行昂贵操作

  • 切勿在 body 内执行 I/O、网络调用或繁重计算
  • 使用 .task {} 进行异步工作——当视图消失时它会自动取消
  • 在滚动视图中谨慎使用 .sensoryFeedback() 和 .geometryGroup()
  • 在列表中尽量减少 .shadow()、.blur() 和 .mask() 的使用——它们会触发离屏渲染

Equatable 一致性

对于含有昂贵 body 的视图,遵循 Equatable 协议以避免不必要的重绘:

struct ExpensiveChartView: View, Equatable {
    let dataPoints: [DataPoint] // DataPoint 必须遵循 Equatable

    static func == (lhs: Self, rhs: Self) -> Bool {
        lhs.dataPoints == rhs.dataPoints
    }

    var body: some View {
        // 复杂的图表渲染
    }
}

预览

使用 #Preview 宏并内联模拟数据以实现快速迭代:

#Preview("空状态") {
    ItemListView(viewModel: ItemListViewModel(repository: EmptyMockRepository()))
}

#Preview("已加载") {
    ItemListView(viewModel: ItemListViewModel(repository: PopulatedMockRepository()))
}

应避免的反模式

  • 在新代码中使用 ObservableObject / @Published / @StateObject / @EnvironmentObject ——请迁移至 @Observable
  • 将异步工作直接放在 body 或 init 中 —— 使用 .task {} 或显式加载方法
  • 在不拥有数据的子视图中将 ViewModel 创建为 @State —— 改为从父视图传递
  • 使用 AnyView 进行类型擦除 —— 对于条件视图,优先使用 @ViewBuilder 或 Group
  • 在向 actor 传递数据或从中接收数据时忽略 Sendable 要求

参考资料

参见技能:swift-actor-persistence 获取基于 actor 的持久化模式。 参见技能:swift-protocol-di-testing 获取基于协议的依赖注入和 Swift Testing 测试方法。

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

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

Next.js 16+ uses App Router with Server Components by default. Client Components are only used when interactivity is needed (hooks, event handlers, browser APIs).

ComeOnOliver/skillshub

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

相关技能