Modèles d'interface SwiftUI

VérifiéSûr

Bonnes pratiques et exemples pour construire des vues SwiftUI, y compris les hiérarchies de navigation, les modificateurs personnalisés et les mises en page adaptatives.

Spar Skills Guide Bot
DeveloppementIntermédiaire
22/07/2026
Claude CodeCursor
#swiftui#ios#ui-components#state-management#navigation

Recommandé pour

Synthèse automatique

Guide de bonnes pratiques et d'exemples pour construire des vues et composants SwiftUI : hiérarchies de navigation, modificateurs personnalisés, mises en page responsives et gestion de l'état.

Points forts

  • Fournit un tableau de décision clair sur la propriété de l'état (@State, @Binding, @Observable, @Environment) selon la cible iOS
  • Donne des règles concrètes pour les sheets (.sheet(item:), dismiss() interne) et les révélations liées au scroll
  • Propose des parcours distincts pour un projet existant (alignement sur les conventions locales) et pour un nouveau scaffolding (TabView + NavigationStack)
  • Renvoie vers des références ciblées par composant plutôt que d'imposer un modèle unique

Limites

  • Le contenu fourni s'arrête au début de la section « Cross-cutting references », donc plusieurs fichiers de référence cités ne sont pas inclus ici
  • Fortement orienté iOS/SwiftUI ; peu utile pour UIKit, macOS ou d'autres frameworks UI
  • Suppose une familiarité avec Swift et les API SwiftUI récentes, notamment l'Observation iOS 17+
Quand l'utiliser

À utiliser lorsqu'on crée ou refactorise une interface SwiftUI, qu'on conçoit une architecture d'onglets ou qu'on hésite sur le bon wrapper d'état à employer.

Quand l'éviter

À éviter pour du développement UIKit, Android ou web, ou lorsque le projet impose une architecture MVVM avec view models obligatoires que ce skill décourage.

Analyse de sécurité

Sûr
Score qualité88/100

The skill provides declarative guidance for SwiftUI UI development, with no declared tools and no instructions for executing commands, network access, file modification, or data handling. It is purely advisory and poses no meaningful execution risk.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

New tabbed app skeleton
Scaffold a new SwiftUI app with a TabView of three tabs (Home, Search, Profile), each wrapping its own NavigationStack, plus a shared router for pushing detail screens. Use the patterns from this skill.
Refactor state ownership
This SwiftUI settings screen uses @ObservedObject and a big view model for everything. Refactor it to use @State, @Binding, and @Observable where appropriate, keeping the same behavior on iOS 17+.
Sheet with selected item
Convert my .sheet(isPresented:) editor into a .sheet(item:) driven by the selected model, and make the sheet own its Save/Cancel actions with dismiss().

name: swiftui-ui-patterns description: Best practices and example-driven guidance for building SwiftUI views and components, including navigation hierarchies, custom view modifiers, and responsive layouts with stacks and grids. Use when creating or refactoring SwiftUI UI, designing tab architecture with TabView, composing screens with VStack/HStack, managing @State or @Binding, building declarative iOS interfaces, or needing component-specific patterns and examples.

SwiftUI UI Patterns

Quick start

Choose a track based on your goal:

Existing project

  • Identify the feature or screen and the primary interaction model (list, detail, editor, settings, tabbed).
  • Find a nearby example in the repo with rg "TabView\(" or similar, then read the closest SwiftUI view.
  • Apply local conventions: prefer SwiftUI-native state, keep state local when possible, and use environment injection for shared dependencies.
  • Choose the relevant component reference from references/components-index.md and follow its guidance.
  • If the interaction reveals secondary content by dragging or scrolling the primary content away, read references/scroll-reveal.md before implementing gestures manually.
  • Build the view with small, focused subviews and SwiftUI-native data flow.

New project scaffolding

  • Start with references/app-wiring.md to wire TabView + NavigationStack + sheets.
  • Add a minimal AppTab and RouterPath based on the provided skeletons.
  • Choose the next component reference based on the UI you need first (TabView, NavigationStack, Sheets).
  • Expand the route and sheet enums as new screens are added.

General rules to follow

  • Use modern SwiftUI state (@State, @Binding, @Observable, @Environment) and avoid unnecessary view models.
  • If the deployment target includes iOS 16 or earlier and cannot use the Observation API introduced in iOS 17, fall back to ObservableObject with @StateObject for root ownership, @ObservedObject for injected observation, and @EnvironmentObject only for truly shared app-level state.
  • Prefer composition; keep views small and focused.
  • Use async/await with .task and explicit loading/error states. For restart, cancellation, and debouncing guidance, read references/async-state.md.
  • Keep shared app services in @Environment, but prefer explicit initializer injection for feature-local dependencies and models. For root wiring patterns, read references/app-wiring.md.
  • Prefer the newest SwiftUI API that fits the deployment target and call out the minimum OS whenever a pattern depends on it.
  • Maintain existing legacy patterns only when editing legacy files.
  • Follow the project's formatter and style guide.
  • Sheets: Prefer .sheet(item:) over .sheet(isPresented:) when state represents a selected model. Avoid if let inside a sheet body. Sheets should own their actions and call dismiss() internally instead of forwarding onCancel/onConfirm closures.
  • Scroll-driven reveals: Prefer deriving a normalized progress value from scroll offset and driving the visual state from that single source of truth. Avoid parallel gesture state machines unless scroll alone cannot express the interaction.

State ownership summary

Use the narrowest state tool that matches the ownership model:

| Scenario | Preferred pattern | | --- | --- | | Local UI state owned by one view | @State | | Child mutates parent-owned value state | @Binding | | Root-owned reference model on iOS 17+ | @State with an @Observable type | | Child reads or mutates an injected @Observable model on iOS 17+ | Pass it explicitly as a stored property | | Shared app service or configuration | @Environment(Type.self) | | Legacy reference model on iOS 16 and earlier | @StateObject at the root, @ObservedObject when injected |

Choose the ownership location first, then pick the wrapper. Do not introduce a reference model when plain value state is enough.

Cross-cutting references

  • references/navigationstack.md: navigation ownership, per-tab history, and enum routing.
  • references/sheets.md: centralized modal presentation and enum-driven sheets.
  • references/deeplinks.md: URL handling and routing external links into app destinations.
  • references/app-wiring.md: root dependency graph, environment usage, and app shell wiring.
  • references/async-state.md: .task, .task(id:), cancellation, debouncing, and async UI state.
  • references/previews.md: #Preview, fixtures, mock environments, and isolated preview setup.
  • references/performance.md: stable identity, observation scope, lazy containers, and render-cost guardrails.

Anti-patterns

  • Giant views that mix layout, business logic, networking, routing, and formatting in one file.
  • Multiple boolean flags for mutually exclusive sheets, alerts, or navigation destinations.
  • Live service calls directly inside body-driven code paths instead of view lifecycle hooks or injected models/services.
  • Reaching for AnyView to work around type mismatches that should be solved with better composition.
  • Defaulting every shared dependency to @EnvironmentObject or a global router without a clear ownership reason.

Workflow for a new SwiftUI view

  1. Define the view's state, ownership location, and minimum OS assumptions before writing UI code.
  2. Identify which dependencies belong in @Environment and which should stay as explicit initializer inputs.
  3. Sketch the view hierarchy, routing model, and presentation points; extract repeated parts into subviews. For complex navigation, read references/navigationstack.md, references/sheets.md, or references/deeplinks.md. Build and verify no compiler errors before proceeding.
  4. Implement async loading with .task or .task(id:), plus explicit loading and error states when needed. Read references/async-state.md when the work depends on changing inputs or cancellation.
  5. Add previews for the primary and secondary states, then add accessibility labels or identifiers when the UI is interactive. Read references/previews.md when the view needs fixtures or injected mock dependencies.
  6. Validate with a build: confirm no compiler errors, check that previews render without crashing, ensure state changes propagate correctly, and sanity-check that list identity and observation scope will not cause avoidable re-renders. Read references/performance.md if the screen is large, scroll-heavy, or frequently updated. For common SwiftUI compilation errors — missing @State annotations, ambiguous ViewBuilder closures, or mismatched generic types — resolve them before updating callsites. If the build fails: read the error message carefully, fix the identified issue, then rebuild before proceeding to the next step. If a preview crashes, isolate the offending subview, confirm its state initialisation is valid, and re-run the preview before continuing.

Component references

Use references/components-index.md as the entry point. Each component reference should include:

  • Intent and best-fit scenarios.
  • Minimal usage pattern with local conventions.
  • Pitfalls and performance notes.
  • Paths to existing examples in the current repo.

Adding a new component reference

  • Create references/<component>.md.
  • Keep it short and actionable; link to concrete files in the current repo.
  • Update references/components-index.md with the new entry.

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/swiftui-ui-patterns-mrwakg7e/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/swiftui-ui-patterns-mrwakg7e' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/swiftui-ui-patterns-mrwakg7e/download' --output '.skill-downloads/swiftui-ui-patterns-mrwakg7e/SKILL.md.part' && mv '.skill-downloads/swiftui-ui-patterns-mrwakg7e/SKILL.md.part' '.skill-downloads/swiftui-ui-patterns-mrwakg7e/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/swiftui-ui-patterns-mrwakg7e/SKILL.md' && test -s '.skill-downloads/swiftui-ui-patterns-mrwakg7e/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/swiftui-ui-patterns' && cp -R '.skill-downloads/swiftui-ui-patterns-mrwakg7e' '.claude/skills/swiftui-ui-patterns'

Cursor
test -f '.skill-downloads/swiftui-ui-patterns-mrwakg7e/SKILL.md' && test -s '.skill-downloads/swiftui-ui-patterns-mrwakg7e/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/swiftui-ui-patterns' && cp -R '.skill-downloads/swiftui-ui-patterns-mrwakg7e' '.cursor/skills/swiftui-ui-patterns'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/swiftui-ui-patterns-mrwakg7e'

openskills read 'swiftui-ui-patterns-mrwakg7e'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/swiftui-ui-patterns-mrwakg7e/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires