Communitygithub.com

ComeOnOliver/skillshub

在實作 SwiftUI 搜尋功能時使用 — 涵蓋 .searchable、isSearching、搜尋建議、搜尋範圍、搜尋 Token 以及程式化搜尋控制 (iOS 15-18)。如需 iOS 26 的搜尋改良功能(底部對齊、最小化工具列、搜尋標籤角色),請參閱 swiftui-26-ref。

skillshub 是什麼?

此技能提供完整的 SwiftUI 搜尋 API 參考指南,專注於環境驅動且由導航容器消耗的搜尋機制。開發者可以學習如何使用 `.searchable()` 修飾器、`isSearching` 與 `dismissSearch` 環境變數、搜尋建議搭配 `.searchCompletion()`、搜尋範圍 (`.searchScopes`) 以及搜尋 Token (`.searchable(text:tokens:)`),並涵蓋從 iOS 15 到 18 的各版本功能,包含 iOS 18 的 `.searchFocused()` 程式化焦點控制。該技能以 iOS 平台為主要支援對象,但也適用於 macOS、tvOS 和 watchOS。詳細的 SKILL.md 文件提供了多個程式碼範例,闡明常見的搜尋錯誤(如搜尋欄未出現)的除錯方法,並解釋如何在 NavigationStack、NavigationSplitView 和 TabView 中正確實作搜尋,以及如何在過濾即輸入和提交式搜尋之間做出選擇。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/CharlesWiltgen/Axiom/axiom-swiftui-search-ref

在你喜歡的 AI 中提問

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

說明文件

SwiftUI 搜尋 API 參考指南

概述

SwiftUI 搜尋是以環境為基礎並由導航容器消耗的。您將 .searchable() 附加到一個視圖上,但實際的搜尋欄是由導航容器(NavigationStack、NavigationSplitView 或 TabView)來呈現的。這種間接性是大多數搜尋錯誤的根源。

API 演進

iOS關鍵新增功能
15.searchable(text:)、isSearching、dismissSearch、建議、.searchCompletion()、onSubmit(of: .search)
16搜尋範圍 (.searchScopes)、搜尋 Token (.searchable(text:tokens:))、SearchScopeActivation
16.4搜尋範圍的 activation 參數 (.onTextEntry、.onSearchPresentation)
17isPresented 參數、suggestedTokens 參數
17.1.searchPresentationToolbarBehavior(.avoidHidingContent)
18用於程式化焦點控制的 .searchFocused($isFocused)
26底部對齊搜尋、.searchToolbarBehavior(.minimize)、Tab(role: .search)、DefaultToolbarItem(kind: .search) — 請參閱 axiom-swiftui-26-ref

何時使用此技能

  • 為 SwiftUI 列表或集合新增搜尋功能
  • 實作輸入即過濾或基於提交的搜尋
  • 新增附自動完成功能的搜尋建議
  • 使用搜尋範圍按類別縮小結果範圍
  • 使用搜尋 Token 進行結構化查詢
  • 程式化控制搜尋焦點
  • 除錯「搜尋欄未出現」的問題

如需 iOS 26 搜尋功能(底部對齊、最小化工具列、搜尋標籤角色),請參閱 axiom-swiftui-26-ref。


第一部分:searchable 修飾器

核心 API

.searchable(
    text: Binding<String>,
    placement: SearchFieldPlacement = .automatic,
    prompt: LocalizedStringKey
)

可用性:iOS 15+、macOS 12+、tvOS 15+、watchOS 8+

運作方式

  1. 您將 .searchable(text: $query) 附加到一個視圖上
  2. 最近的導航容器(NavigationStack、NavigationSplitView)會呈現搜尋欄
  3. 該視圖透過環境接收 isSearching 和 dismissSearch
  4. 您的視圖根據綁定的文字進行過濾或查詢
struct RecipeListView: View {
    @State private var searchText = ""
    let recipes: [Recipe]

    var body: some View {
        NavigationStack {
            List(filteredRecipes) { recipe in
                NavigationLink(recipe.name, value: recipe)
            }
            .navigationTitle("食譜")
            .searchable(text: $searchText, prompt: "尋找食譜")
        }
    }

    var filteredRecipes: [Recipe] {
        if searchText.isEmpty { return recipes }
        return recipes.filter { $0.name.localizedCaseInsensitiveContains(searchText) }
    }
}

放置選項

放置方式行為
.automatic系統決定(建議使用)
.navigationBarDrawer導航列標題下方 (iOS)
.navigationBarDrawer(displayMode: .always)始終可見,滾動時不隱藏
.sidebar側邊欄中 (NavigationSplitView)
.toolbar工具列區域
.toolbarPrincipal工具列的主要區域

陷阱:如果視圖層級不支援,SwiftUI 可能會忽略您的放置偏好。請務必在目標平台上進行測試。

NavigationSplitView 中的欄位關聯

您附加 .searchable 的位置決定了哪個欄位會顯示搜尋欄:

NavigationSplitView {
    SidebarView()
        .searchable(text: $query)  // 在側邊欄中搜尋
} detail: {
    DetailView()
}

// 相較於

NavigationSplitView {
    SidebarView()
} detail: {
    DetailView()
        .searchable(text: $query)  // 在詳細欄位中搜尋
}

// 相較於

NavigationSplitView {
    SidebarView()
} detail: {
    DetailView()
}
.searchable(text: $query)  // 系統決定欄位

第二部分:顯示搜尋結果

isSearching 環境變數

@Environment(\.isSearching) private var isSearching

可用性:iOS 15+

當使用者啟動搜尋(點擊欄位)時變為 true,當他們取消或您呼叫 dismissSearch 時變為 false。

關鍵規則:isSearching 必須從具有 .searchable 的視圖的子視圖中讀取。SwiftUI 在可搜尋視圖的環境中設定該值,但不會向上傳播。

// 模式:搜尋時覆蓋搜尋結果
struct WeatherCityList: View {
    @State private var searchText = ""

    var body: some View {
        NavigationStack {
            // SearchResultsOverlay 會讀取 isSearching
            SearchResultsOverlay(searchText: searchText) {
                List(favoriteCities) { city in
                    CityRow(city: city)
                }
            }
            .searchable(text: $searchText)
            .navigationTitle("天氣")
        }
    }
}

struct SearchResultsOverlay<Content: View>: View {
    let searchText: String
    @ViewBuilder let content: Content
    @Environment(\.isSearching) private var isSearching

    var body: some View {
        if isSearching {
            // 顯示搜尋結果
            SearchResults(query: searchText)
        } else {
            content
        }
    }
}

dismissSearch 環境變數

@Environment(\.dismissSearch) private var dismissSearch

可用性:iOS 15+

呼叫 dismissSearch() 會清除搜尋文字、移除焦點,並將 isSearching 設為 false。必須從可搜尋視圖的層級內部呼叫。

struct SearchResults: View {
    @Environment(\.dismissSearch) private var dismissSearch

    var body: some View {
        List(results) { result in
            Button(result.name) {
                selectResult(result)
                dismissSearch()  // 選取後關閉搜尋
            }
        }
    }
}

第三部分:搜尋建議

新增建議

將 suggestions 閉包傳遞給 .searchable:

.searchable(text: $searchText) {
    ForEach(suggestedResults) { suggestion in
        Text(suggestion.name)
            .searchCompletion(suggestion.name)
    }
}

可用性:iOS 15+

當使用者正在輸入時,建議會顯示在搜尋欄下方的一個列表中。

searchCompletion 修飾器

.searchCompletion(_:) 將一個建議綁定到一個完成值。當使用者點擊建議時,搜尋文字會被替換為該完成值。

.searchable(text: $searchText) {
    ForEach(matchingColors) { color in
        HStack {
            Circle()
                .fill(color.value)
                .frame(width: 16, height: 16)
            Text(color.name)
        }
        .searchCompletion(color.name)  // 點擊後將搜尋文字填入顏色名稱
    }
}

沒有 .searchCompletion():建議會顯示,但點擊它們對搜尋欄沒有任何作用。這是最常見的建議錯誤。

完整建議模式

struct ColorSearchView: View {
    @State private var searchText = ""
    let allColors: [NamedColor]

    var body: some View {
        NavigationStack {
            List(filteredColors) { color in
                ColorRow(color: color)
            }
            .navigationTitle("顏色")
            .searchable(text: $searchText, prompt: "搜尋顏色") {
                ForEach(suggestedColors) { color in
                    Label(color.name, systemImage: "paintpalette")
                        .searchCompletion(color.name)
                }
            }
        }
    }

    var suggestedColors: [NamedColor] {
        guard !searchText.isEmpty else { return [] }
        return allColors.filter {
            $0.name.localizedCaseInsensitiveContains(searchText)
        }
        .prefix(5)
        .map { $0 }  // 將 ArraySlice 轉換為 Array
    }

    var filteredColors: [NamedColor] {
        if searchText.isEmpty { return allColors }
        return allColors.filter {
            $0.name.localizedCaseInsensitiveContains(searchText)
        }
    }
}

第四部分:搜尋提交

onSubmit(of: .search)

當使用者在搜尋欄中按下 Return/Enter 時觸發:

.searchable(text: $searchText)
.onSubmit(of: .search) {
    performSearch(searchText)
}

可用性:iOS 15+

過濾 vs 提交決策

模式使用時機範例
輸入即過濾本地資料、快速過濾聯絡人、設定
基於提交的搜尋網路請求、昂貴的查詢App Store、網頁搜尋
組合模式建議在本地過濾,提交觸發伺服器地圖、購物

組合建議 + 提交模式

struct StoreSearchView: View {
    @State private var searchText = ""
    @State private var searchResults: [Product] = []
    let recentSearches: [String]

    var body: some View {
        NavigationStack {
            List(searchResults) { product in
                ProductRow(product: product)
            }
            .navigationTitle(\

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

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

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

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相關技能