Communitygithub.com

ComeOnOliver/skillshub

SwiftUI 架構模式、使用 @Observable 的狀態管理、視圖組合、導航、效能最佳化以及現代 iOS/macOS UI 最佳實踐。

skillshub 是什麼?

此技能全面涵蓋現代 SwiftUI 開發的核心模式,專注於 Apple 平台上宣告式、高效能的使用者介面建構。它深入介紹了基於 `@Observable` 的狀態管理,取代了舊有的 `ObservableObject` 模式,並提供清晰的 property wrapper 選擇指南。技能還包含了視圖組合策略,透過提取子視圖和 `ViewModifier` 來提升程式碼重用與渲染效率。在導航方面,它說明了如何使用 `NavigationStack` 進行型別安全的路由設計,並在效能章節中提供了使用 lazy container、穩定識別碼以及避免在 `body` 中執行昂貴操作的實用建議。此外,該技能也指出了應避免的反模式,並整合了相關技能的參考資料。

相容平台~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 模式

現代 SwiftUI 模式,用於在 Apple 平台上建構宣告式、高效能的使用者介面。涵蓋 Observation 框架、視圖組合、型別安全導航以及效能最佳化。

何時啟用

  • 建構 SwiftUI 視圖並管理狀態(@State、@Observable、@Binding)
  • 使用 NavigationStack 設計導航流程
  • 建構視圖模型和資料流程
  • 最佳化列表和複雜佈局的渲染效能
  • 在 SwiftUI 中使用環境值和依賴注入

狀態管理

Property Wrapper 選擇

選擇最適合的簡潔 wrapper:

Wrapper使用場景
@State視圖區域的數值類型(切換開關、表單欄位、sheet 呈現)
@Binding對父視圖 @State 的雙向參考
@Observable class + @State擁有多個屬性的自有模型
@Observable class(無 wrapper)從父視圖傳入的唯讀參考
@Bindable對 @Observable 屬性的雙向綁定
@Environment透過 .environment() 注入的共享依賴

@Observable 視圖模型

使用 @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 ?? "訪客")
    }
}

視圖組合

提取子視圖以限制無效化

將視圖拆分為小型、專注的結構。當狀態變更時,僅有讀取該狀態的子視圖會重新渲染:

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)
    }
}

效能

使用 Lazy Container 處理大型集合

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 {} 處理非同步工作——它會在視圖消失時自動取消
  • 在 scroll view 中節制使用 .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 {} 或明確的 load 方法
  • 在未擁有資料的子視圖內部將視圖模型建立為 @State——應從父視圖傳入
  • 使用 AnyView 型別抹消——偏好使用 @ViewBuilder 或 Group 處理條件視圖
  • 在將資料傳入/傳出 actor 時忽略 Sendable 要求

參考資料

請參閱技能:swift-actor-persistence 以取得基於 actor 的持久化模式。 請參閱技能:swift-protocol-di-testing 以取得使用 Swift Testing 進行協定型 DI 和測試的資訊。

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

相關技能