Communitygithub.com

SwiftUI 專家

建立乾淨、高效能、無障礙的 SwiftUI 視圖,具備正確的狀態所有權、範圍化的失效處理與流暢的列表滾動,並能針對給定的畫面時間與重新渲染預算審查現有 SwiftUI 程式碼。當有人問「為什麼我的 SwiftUI 列表會卡頓」、「應該用 @State 還是 @Observable」、「我的整個畫面在單一行變更時重新渲染」、「如何設計這個轉場動畫」,或需要建立或重構 SwiftUI 視圖時使用。

SwiftUI 專家 是什麼?

此技能專精於 SwiftUI 視圖的設計與審查,核心在於正確的「狀態所有權」與「失效範圍控制」。它能幫助開發者分析狀態應該存在於哪個視圖層級、使用哪種包裝器(@State、@Binding、@Observable、@Environment),並透過提煉子視圖與最小化資料傳遞,將因狀態變更而導致的重新渲染範圍縮小到最小。技能支援 iOS 平台,預設假設 ProMotion 120Hz 與 60Hz 基準裝置,並提供基於幀預算(8.3ms/120Hz,16.7ms/60Hz)的列表效能規則,幫助診斷滾動卡頓、動畫撕裂等問題。工作流程從收集輸入(目標裝置、資料形狀、所有權對照表)開始,依序決定狀態所有權、組合視圖、確保列表與動畫效能,最後進行無障礙處理。輸出結果包含可運作的 SwiftUI 程式碼與一份狀態對照表,並能在程式碼審查中以幀預算影響排序列出待修正事項。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/SkillMedev/skills/tree/HEAD/skills/swift-ui

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

SwiftUI 專家 是做什麼的?

一個 SwiftUI 畫面的成敗取決於狀態所有權:將狀態放在錯誤的位置,每次按鍵都會重新評估整個視圖樹,列表卡頓,動畫撕裂。此技能負責建立與審查 SwiftUI 視圖,確保失效範圍限制在實際讀取變更資料的視圖內,幀預算在滾動時得以維持,且結果預設即具備無障礙性,而非事後補救。

操作流程

依照此順序執行,因為狀態設計決定下游一切——在視圖階層建立後才修正狀態,等於重寫整個階層。

步驟 1:收集輸入

撰寫任何視圖程式碼前先收集。若使用者不清楚,則使用預設值並標註為推測。

  • 目標裝置與更新頻率(預設:假設 ProMotion 120Hz iPhone 加上一部 60Hz 基準裝置)。
  • 資料形狀:最大列表中有多少項目、資料變更頻率、是否為串流資料。
  • 所有權對照表:每個狀態由哪個視圖建立、哪些視圖讀取、哪些視圖修改。
  • 超出基本需求的無障礙要求(預設:完整的動態字級 + VoiceOver 支援)。

步驟 2:為每個值選擇狀態所有權

選擇最狹窄且能運作的包裝器:

  • @State - 區域性、視圖自有、值型別狀態。也是視圖建立的 @Observable 模型實例的正確擁有者。
  • @Binding - 雙向參考,指向由其他地方擁有的狀態。僅在子視圖會修改時傳遞 Binding;只讀取時傳遞純值。
  • @Observable(Observation 框架)- 模型物件;視圖僅觀察它們實際讀取的屬性,因此失效是基於屬性而非基於物件。
  • @Environment - 依賴注入,向下傳遞服務與共享模型至視圖樹。

規則:狀態存在於所有讀取或寫入該狀態的視圖的最低共同祖先處——不能更低(否則視圖消失時狀態會重置),也不能更高(否則會擴大失效範圍)。

步驟 3:組合視圖以限制失效範圍

  • 保持 body 精簡;提取子視圖,使變更只影響單一行而不是整個畫面。body 若超過約 50 行或三層巢狀,即應考慮拆分。
  • 傳遞最小資料給子視圖——傳遞 item.title,而非整個資料儲存庫——這樣只有受影響的視圖會重新渲染。
  • 使用 @ViewBuilder 輔助方法取代大型巢狀閉包。
  • 絕不在 body 中執行繁重工作(格式化、排序、篩選、解碼);應在模型中計算,並將完成的值交給視圖。body 必須保持在微秒級別,因為在動畫期間它可能每幀都會執行。

步驟 4:列表與幀預算

幀預算為 120Hz 下每幀 8.3ms,60Hz 下每幀 16.7ms——這是該幀在主執行緒上的總時間,不僅是單一行的時間。實務規則:

  • 超過約 50 行時使用 List 或 LazyVStack,以便按需渲染行;純 VStack 搭配 ScrollView 會一次性建立所有行。
  • 使用資料中的穩定 id(item.id),絕不使用陣列索引或在 body 中計算的 UUID()——不穩定的 id 會破壞行身分識別,導致閃爍、滾動位置遺失以及行狀態遺失。
  • 行必須是固定成本:不要在每行中建立日期格式器或解碼圖片;快取格式器,使用 AsyncImage 或快取圖片管線。
  • 使用 Instruments 的 SwiftUI 模板:在滾動時觀察 view-body 的評估次數。若某種行類型在不相關狀態變更時仍會評估其 body,表示存在狀態所有權錯誤——請修正步驟 2,不要在其周圍使用 memoization。

步驟 5:從狀態驅動動畫

  • 從狀態驅動動畫:withAnimation { model.expanded.toggle() }。
  • 偏好使用 .animation(_:value:) 並指定特定值,而非隱式全域動畫,後者會讓非預期的東西也產生動畫。
  • 使用 matchedGeometryEffect 實現共享元素轉場;使用 transition 實現插入/移除。
  • 尊重 accessibilityReduceMotion:當該設定啟用時,用透明度淡入淡出取代移動效果。

步驟 6:無障礙處理

  • 添加 accessibilityLabel / accessibilityValue;使用 accessibilityElement(children: .combine) 將相關元素分組,使一行讀起來像一個句子,而非五個片段。
  • 尊重動態字級——使用系統文字樣式,不要用固定框架剪裁文字;請在最大的無障礙字級下驗證。
  • 檢查對比度,並為深色模式、大動態字級以及空/載入/錯誤狀態(附範例資料)添加 #Preview 變體。

工作範例:狀態所有權,不良 vs 良好

不良——每次按鍵整個畫面都會失效,因為搜尋文字存在於整個視覺樹都觀察的模型中,且行接收了整個資料儲存庫:

@Observable final class ScreenStore {
  var searchText = ""
  var items: [Item] = []
}

struct ContactList: View {
  @State private var store = ScreenStore()
  var body: some View {
    VStack {
      TextField("搜尋", text: $store.searchText)
      ForEach(store.items) { item in
        ContactRow(store: store, item: item) // 行觀察一切
      }
    }
  }
}

良好——搜尋文字是視圖區域性的,行只取得它們讀取的值,且列表是懶加載且具有穩定 id:

struct ContactList: View {
  @State private var searchText = ""
  @Environment(ContactModel.self) private var model
  var body: some View {
    List(model.filtered(searchText)) { item in
      ContactRow(name: item.name, isOnline: item.isOnline)
    }
    .searchable(text: $searchText)
  }
}

struct ContactRow: View {
  let name: String
  let isOnline: Bool
  var body: some View {
    Label(name, systemImage: isOnline ? "circle.fill" : "circle")
  }
}

在良好版本中輸入文字只會使 List 的內容閉包以及那些因篩選而改變所屬關係的行失效——不影響其他東西。

交付物

產出可運作的 SwiftUI 視圖程式碼,以及一段描述狀態對照表的段落,說明每個狀態的:擁有者、包裝器、以及哪些視圖讀取或寫入它。對於程式碼審查,產出一份按幀預算影響排序的發現清單,每個發現附帶修正方式。

請勿

  • 絕不在 body 評估期間修改狀態——這會導致迴圈或觸發未定義行為警告。
  • 不要在 onAppear 中使用原始 Task 執行非同步工作——請使用 .task {},它會在不可見時自動取消。
  • 不要將視圖型別(Color、Image、AnyView)放入模型中;模型必須在沒有 UI 的情況下仍可測試。
  • 不要「為求簡潔」將所有狀態提升到一個畫面層級的儲存庫——這正是導致每次按鍵都重繪畫面的模式。
  • 不要在使用 equatable() 或快取來修正所有權錯誤之前掩蓋失效問題;該錯誤會在觀察同一物件的下一個視圖中再次浮現。
  • 不要在文字上使用固定框架——動態字級會將它裁剪。

品質標準

一個完成的視圖必須符合以下條件:

  • 每個狀態都只有一個擁有者,且使用最狹窄且能運作的包裝器。
  • Instruments 顯示行 body 僅在其自身資料變更時才被評估。
  • 滾動預期最大的列表時,在 60Hz 基準裝置上能維持幀預算。
  • 長生命週期的狀態被提升到任何可能消失的視圖之上,使其在導覽後仍然存活。
  • 處理了鍵盤迴避與安全區域(safeAreaInset、scrollDismissesKeyboard)。
  • VoiceOver 能讀取每個互動元素且帶有意義的標籤;佈局在最大的動態字級下仍能存活;reduceMotion 受到尊重。
  • 存在載入、空、錯誤、深色模式以及大字級狀態的預覽畫面。

若需進行超出單一畫面的應用程式層級效能分析,請搭配 mobile-perf-profiler。

Individual skills in this repo

This repo contains 19 individual skills — each has its own dedicated page.

SkillMedev/skills

Designs REST API surfaces - resource naming, HTTP method and status-code semantics, error shapes, pagination, and filtering - and delivers an endpoint spec a consumer can build against without asking questions. Use when someone asks "how should I name this endpoint", "what status code should this return", "should this be PUT or PATCH", "how do I paginate this list", or is reviewing an API before it ships to external consumers. Do NOT use for planning breaking-change rollouts and deprecation windows - use api-versioning-strategist instead; for GraphQL type and resolver design - use graphql-schema instead; for generating client SDKs from an existing spec - use api-client-generator instead; for designing inbound webhook endpoints - use webhook-receiver-hardener instead.

SkillMedev/skills

Produce an accurate, properly timed caption track (SRT or WebVTT) from a video's audio - transcribing or aligning to the voiceover script, timing cues to speech, and enforcing line-length and reading-speed rules so captions are readable and in sync. Use when someone says "generate captions", "make subtitles from the audio", "transcribe and caption this", "export an SRT or VTT", "the captions are out of sync", or "the subtitles flash by too fast to read". Do NOT use to burn-in, style, reframe, or position an existing caption track for a platform (9:16, brand styling, safe areas) - that is social-video-formatter; do NOT use to animate text word-by-word as a motion graphic - that is kinetic-typography; do NOT use to write the spoken script in the first place - that is narration-script.

SkillMedev/skills

Turns data and charts into a decision-driving narrative structured as headline finding, trend, implication, and recommended action - with finding-led chart titles, context for every number, annotation guidance, and honest flags on any conclusion the data cannot support. Use when someone says "turn these numbers into a story", "what's the takeaway from this data", "help me present these results to leadership", or has charts but no narrative. Do NOT use for compressing a long document into a one-pager - use executive-summary instead - or for running the analysis that produces the findings - use eda-playbook instead.

SkillMedev/skills

Use when a task needs live or historical money data - "convert USD to EUR", "current/past exchange rate", "FX rate on this date / over this range", or "current price of Bitcoin/Ethereum, market cap, 24h change". Frankfurter (ECB reference rates, no key) is the FX default; CoinGecko's free keyless tier covers crypto. Do NOT use for stock quotes or equities - no keyless stock API survives verification, say so instead of guessing; do NOT use for country economic indicators like GDP or inflation series - use government-open-data instead; if the request is a vague "I need live data", route through public-data-api-picker.

SkillMedev/skills

Builds a driver-based FP&A operating model linking business inputs to P&L, balance sheet, and cash flow outputs. Use when building an annual plan, preparing investor materials, running scenario analysis, or stress-testing the business.

SkillMedev/skills

Use when a task needs live geographic lookups - "geocode this address", "what's at these coordinates" (reverse geocoding), "lat/lon for this city", "which country/state is this ZIP or postal code in", or "country facts: capital, currency, population, flag". Nominatim (OpenStreetMap) is the geocoding default; Zippopotam for postal codes; APICountries for country facts. All keyless. Do NOT use for weather at a location - use weather-climate instead; do NOT use for country-level statistics over time (GDP, population trends) - use government-open-data instead; if the request is a vague "I need live data", route through public-data-api-picker.

SkillMedev/skills

Runs the full Getting Things Done loop - capture, clarify, organize, reflect, engage - building a trusted system of context lists, a projects list with defined next actions, and a weekly review habit. Use when someone says "I'm overwhelmed and things are slipping through the cracks", "set up GTD for me", "help me do a brain dump and organize it", or "my to-do list is a mess". Do NOT use for just running the weekly review ritual itself - use weekly-review instead - or for clearing an email backlog - use inbox-zero.

SkillMedev/skills

Processes any email backlog to zero using the 4Ds - Delete, Delegate, Defer, Do - with a mass-archive strategy for the obvious, a touch-each-email-once discipline, and a keep-it-clear system of batched processing windows, ruthless unsubscribing, filters, and a minimal folder setup. Use when someone says "I have 5,000 unread emails", "help me get to inbox zero", "email is eating my whole day", or treats their inbox as a to-do list. Do NOT use for drafting the reply emails themselves or prioritization rules for an ongoing support queue - use email-triage instead - or for protecting focus time around the email windows - use deep-work-planner instead.

SkillMedev/skills

Write landing-page copy section by section - hero, social proof, features-as-benefits, objections, CTA - leading with one promise and proving it down the page. Use when someone asks "write my landing page", "improve my hero headline", "what should the homepage say", "turn these features into benefits", or is shipping a new page for a launch or campaign. Do NOT use for testing and optimizing an existing page's conversion rate - use landing-page-cro instead; for the one-line claim itself use positioning-statement; for the full message ladder use messaging-hierarchy.

SkillMedev/skills

Improves an existing landing page's conversion rate through evidence-first CRO - audit heatmaps and recordings, write structured hypotheses, prioritize with ICE scoring, and run one-variable tests to statistical significance. Use when someone asks "why isn't my landing page converting", "audit this page before we scale spend", "which A/B test should we run first", or after a CVR drop or ahead of a paid-traffic push. Do NOT use for writing a new landing page from scratch - use landing-page-copy instead. Do NOT use for auditing the ad accounts sending the traffic - use paid-acquisition-audit instead. Do NOT use for reading the results of a finished experiment - use ab-test-analyzer instead.

SkillMedev/skills

Runs structured coaching sessions using values clarification and the GROW model, ending every session with one committed action, a deadline, and an if-then plan for the likely obstacle. Use when someone says "I feel stuck in my life", "help me figure out what I want", "hold me accountable to my goals", or "coach me through this decision". Do NOT use for building a stress toolkit - use stress-management instead - or a journaling practice - use journal-framework; for a standing goal-tracking system, use goals-accountability. Coaching, not therapy: signs of clinical distress route to a licensed professional.

SkillMedev/skills

Adapts English content for a target language and region - swapping idioms, setting the right formality register, replacing cultural references, converting dates, units, and currency - and delivers the localized text with a notes column explaining each adaptation and flagging what needs a native reviewer. Use when someone asks "localize this copy for the Japanese market", "adapt our marketing copy for the Mexican market", "make this translation sound native instead of literal", or a literal translation reads foreign, stiff, or risky. Do NOT use for auditing in-product UI text quality - use ux-writing-audit instead.

SkillMedev/skills

Turns a natural-language video brief into a complete, ready-to-preview Remotion composition - extracts duration, scenes, brand colors, aspect ratio, and real copy; plans the frame budget; and writes data-driven React/TypeScript using useCurrentFrame, interpolate, spring, AbsoluteFill, and Sequence, registered in Root.tsx. Use when someone says "build a 20-second product demo video", "animate a feature walkthrough", "write the Remotion code for this marketing clip", or wants a scene-by-scene composition they can scrub in Studio. Do NOT use for rendering, iterating, or batching the finished MP4 - use remotion-render instead - or for installing and scaffolding the project - use remotion-setup instead.

SkillMedev/skills

Scaffolds a new Remotion video project wired for Claude Code Agent Skills - Node check, create-video scaffold, skills install, folder conventions, Google Fonts, and a smoke-test render. Use whenever someone wants to start making videos with Remotion and Claude, even just "make product videos with Claude.

SkillMedev/skills

Classifies incident severity (SEV1-4) using impact, scope, and urgency signals and decides who to page. Use when an alert fires or a report comes in and a severity call must be made quickly.

SkillMedev/skills

Use the Skill Me catalog from inside any conversation - discover, install, and manage Claude skills through the Skill Me MCP, and load installed skills automatically each session.

SkillMedev/skills

Write one platform-native caption from a topic and brand voice, with a front-loaded hook, native length, and a single earned CTA. Use when the user gives a topic (and optionally brand voice or a described image/video) and asks for an Instagram, LinkedIn, X/Twitter, or TikTok caption. Do NOT use when the user wants a dedicated standalone LinkedIn post - use linkedin-post-writer instead; or a multi-post X thread - use tweet-thread-builder instead; or to adapt one existing piece of content into versions for several channels - use cross-platform-reformatter instead.

SkillMedev/skills

Reframe and export a finished video for social platforms - 9:16 ↔ 16:9 cropping, burned-in captions, a platform-native first frame, loop design, and per-platform specs (aspect, length, safe areas) for TikTok, Reels, Shorts, X, and LinkedIn. Use when someone says "make this vertical", "crop to 9:16", "format for TikTok/Reels/Shorts", "add captions/subtitles", "why is my video cut off on mobile", "resize for Instagram", or "export for social". Do NOT use when the question is about the storyboard or shot order before any video exists (use video-storyboard); the animation craft of how elements move (use motion-design-principles); animated word-by-word caption styling (use kinetic-typography); palette, contrast, or lighting (use motion-color-and-light); directing the product-demo content and screen choreography (use product-demo-director); or scoring, beat-syncing, or audio (use sound-and-music-sync) - this is the craft layer that decides WHAT to format for the feed, then hands a concrete spec to remotion-compo...

SkillMedev/skills

Writes and tunes PySpark jobs - join strategy and broadcast size limits, shuffle-partition sizing, skew diagnosis and salting, UDF avoidance, caching, and output file layout - with concrete size and skew thresholds. Use when someone asks "why is my Spark job slow", "should I broadcast this join", "one task takes forever while the rest finish", "my job OOMs during a join", or is writing a new PySpark ETL job. Do NOT use for Kafka topic, consumer-group, or streaming-pipeline design - use kafka-pipelines instead; do NOT use for single-machine dataframe work that fits in memory - use pandas-expert instead.

相關技能