Перейти к содержанию
Skillpedia
Сайты и интерфейсы (фронтенд)48k · #5914

swiftui-ui-patterns

Что он делает

Это руководство помогает организовать код приложений, созданных на SwiftUI. Оно показывает, как управлять навигацией между экранами, открывать дополнительные окна (модальные окна, или sheets), обрабатывать долгие задачи и создавать повторно используемые части интерфейса.

Когда использовать

  • ✓Когда вы создаете новые экраны или части приложения на SwiftUI.
  • ✓Когда нужно продумать, как пользователь переходит между экранами.
  • ✓Когда вы хотите создавать компоненты интерфейса, которые можно использовать в нескольких местах.

Ссылка на скилл

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/swiftui-ui-patterns/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/swiftui-ui-patterns/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Как организовать навигацию между экранами в SwiftUI?”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Руководство дает примеры и правила использования средств организации SwiftUI, таких как @State и @Binding, и подсказывает, как структурировать код, чтобы его было легче поддерживать и читать.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

SwiftUI UI Patterns

Quick start

When to Use

  • When creating or refactoring SwiftUI screens, flows, or reusable UI components.
  • When you need guidance on navigation, sheets, async state, previews, or component patterns.

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.

Example prerequisites

The references contain application sketches, not a complete app. Supply the named project views, models, adapters and theme tokens; verify imports, actual error contracts and minimum OS with the installed SDK before adapting them. Bind every visible action to a real tested handler, make persistence failures observable and use inert preview data. A successful code example is not evidence of a tested screen or deployed service.

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.

…

Частые вопросы

Что такое «sheets»?

Это небольшие окна, которые появляются поверх основного экрана. Их используют для быстрых действий, например для заполнения формы или показа подробностей, без перехода с текущего экрана.

Что означает «async state»?

Это способ обрабатывать задачи, которые выполняются некоторое время, например загрузку данных из интернета. Сюда входит показ индикатора загрузки и обработка возможных ошибок.

Можно ли использовать это в старых проектах?

Да, руководство предлагает альтернативы для старых версий SwiftUI, но рекомендует по возможности использовать новейшие инструменты.

Подробности

Оригинальное описание автора

Apply proven SwiftUI UI patterns for navigation, sheets, async state, and reusable screens.

repo: sickn33/agentic-awesome-skills

Популярность

Звёзды на GitHub
48k
Место в рейтинге
#5914
Лицензия
MIT
Обновлён
15.10.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы