Communitygithub.com

ComeOnOliver/skillshub

Padrões de arquitetura SwiftUI, gerenciamento de estado com @Observable, composição de views, navegação, otimização de desempenho e melhores práticas de UI modernas para iOS/macOS.

O que é skillshub?

Este skill fornece um guia abrangente sobre padrões modernos de SwiftUI para desenvolvimento em plataformas Apple. Ele abrange desde a escolha correta de property wrappers para gerenciamento de estado, com ênfase no uso do framework `@Observable` em vez do `ObservableObject` obsoleto, até técnicas avançadas de composição de views para limitar a invalidação da interface. O skill também detalha navegação type-safe com `NavigationStack` e `NavigationPath`, otimizações de desempenho como uso de `LazyVStack`, identificadores estáveis, e conformidade com `Equatable`, além de boas práticas para criação de previews com macro `#Preview`. Ideal para desenvolvedores iOS e macOS que buscam criar aplicativos SwiftUI mais previsíveis, performáticos e de fácil manutenção, seguindo as recomendações mais recentes da Apple.

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

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Padrões SwiftUI

Padrões modernos de SwiftUI para construir interfaces de usuário declarativas e performáticas nas plataformas Apple. Abrange o framework Observation, composição de views, navegação type-safe e otimização de desempenho.

Quando Ativar

  • Construindo views SwiftUI e gerenciando estado (@State, @Observable, @Binding)
  • Projetando fluxos de navegação com NavigationStack
  • Estruturando view models e fluxo de dados
  • Otimizando desempenho de renderização para listas e layouts complexos
  • Trabalhando com environment values e injeção de dependência no SwiftUI

Gerenciamento de Estado

Seleção de Property Wrappers

Escolha o wrapper mais simples que se adequar:

WrapperCaso de Uso
@StateValue types locais da view (alternadores, campos de formulário, apresentação de sheets)
@BindingReferência bidirecional ao @State da view pai
Classe @Observable + @StateModelo próprio com múltiplas propriedades
Classe @Observable (sem wrapper)Referência somente leitura passada do pai
@BindableBinding bidirecional a uma propriedade @Observable
@EnvironmentDependências compartilhadas injetadas via .environment()

ViewModel com @Observable

Use @Observable (e não ObservableObject) — ele rastreia mudanças no nível da propriedade, fazendo com que o SwiftUI renderize novamente apenas as views que leem a propriedade alterada:

@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()) ?? []
    }
}

View Consumindo o 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() }
    }
}

Injeção via Environment

Substitua @EnvironmentObject por @Environment:

// Injetar
ContentView()
    .environment(authManager)

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

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

Composição de Views

Extrair Subviews para Limitar Invalidação

Divida views em structs pequenas e focadas. Quando o estado muda, apenas a subview que lê aquele estado é renderizada novamente:

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 para Estilo Reutilizável

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

Navegação

NavigationStack Type-Safe

Use NavigationStack com NavigationPath para roteamento programático e type-safe:

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

Desempenho

Use Contêineres Lazy para Coleções Grandes

LazyVStack e LazyHStack criam views apenas quando estão visíveis:

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

Identificadores Estáveis

Sempre use IDs estáveis e únicos em ForEach — evite usar índices de array:

// Use conformidade a Identifiable ou id explícito
ForEach(items, id: \.stableID) { item in
    ItemRow(item: item)
}

Evite Trabalho Pesado no body

  • Nunca realize I/O, chamadas de rede ou computação pesada dentro de body
  • Use .task {} para trabalho assíncrono — ele cancela automaticamente quando a view desaparece
  • Use .sensoryFeedback() e .geometryGroup() com moderação em scroll views
  • Minimize .shadow(), .blur() e .mask() em listas — eles disparam renderização fora da tela

Conformidade com Equatable

Para views com bodies pesados, conforme a Equatable para evitar re-renderizações desnecessárias:

struct ExpensiveChartView: View, Equatable {
    let dataPoints: [DataPoint] // DataPoint deve conformar a Equatable

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

    var body: some View {
        // Renderização complexa de gráfico
    }
}

Previews

Use a macro #Preview com dados mock inline para iteração rápida:

#Preview("Estado vazio") {
    ItemListView(viewModel: ItemListViewModel(repository: EmptyMockRepository()))
}

#Preview("Carregado") {
    ItemListView(viewModel: ItemListViewModel(repository: PopulatedMockRepository()))
}

Anti-Padrões a Evitar

  • Usar ObservableObject / @Published / @StateObject / @EnvironmentObject em código novo — migre para @Observable
  • Colocar trabalho assíncrono diretamente em body ou init — use .task {} ou métodos de carregamento explícitos
  • Criar view models como @State dentro de views filhas que não possuem os dados — passe do pai
  • Usar AnyView para apagar tipo — prefira @ViewBuilder ou Group para views condicionais
  • Ignorar requisitos de Sendable ao passar dados de/para atores

Referências

Veja o skill: swift-actor-persistence para padrões de persistência baseados em atores. Veja o skill: swift-protocol-di-testing para DI baseada em protocolos e testes com 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

Habilidades Relacionadas