Communitygithub.com

ComeOnOliver/skillshub

用于实现 SwiftUI 搜索 — .searchable、isSearching、搜索建议、范围、标记、编程式搜索控制(iOS 15-18)。如需 iOS 26 搜索优化(底部对齐、最小化工具栏、搜索标签页角色),请参阅 swiftui-26-ref。

skillshub 是什么?

该技能是一个全面的 SwiftUI 搜索 API 参考指南,专注于 `.searchable()` 修饰符及其生态系统。它涵盖了从 iOS 15 到 iOS 18 的搜索功能,包括核心 API、搜索建议、搜索提交、搜索范围(iOS 16+)、搜索标记(iOS 16+)以及编程式搜索控制(iOS 18+)。该技能特别强调了搜索在导航容器(如 NavigationStack、NavigationSplitView、TabView)中的工作方式,并提供了处理常见问题(如搜索字段不显示)的实用模式。对于 iOS 26 的新功能(如底部对齐搜索、最小化工具栏、搜索标签页角色),技能指出了外部参考。它提供了大量代码示例,演示了过滤式输入、提交式搜索、结合建议和提交、使用范围进行类别筛选、使用标记进行结构化查询以及通过 FocusState 进行焦点控制。该技能详细解释了环境属性如 isSearching 和 dismissSearch 的使用,并提供了关键规则,例如 isSearching 必须从 `.searchable()` 的子视图中读取。

兼容平台~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)、搜索标记 (.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 列表或集合添加搜索
  • 实现过滤式输入或提交式搜索
  • 添加带有自动补全的搜索建议
  • 使用搜索范围按类别缩小结果
  • 使用搜索标记进行结构化查询
  • 编程式控制搜索焦点
  • 调试“搜索字段不显示”问题

对于 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("Recipes")
            .searchable(text: $searchText, prompt: "Find a recipe")
        }
    }

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

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()  // 选择后关闭搜索
            }
        }
    }
}

第三部分:搜索建议

添加建议

向 .searchable 传递一个 suggestions 闭包:

.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("Colors")
            .searchable(text: $searchText, prompt: "Search colors") {
                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+

过滤与提交决策

模式适用场景示例
过滤式输入本地数据、快速过滤联系人、设置
提交式搜索网络请求、昂贵查询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("Store")
            .searchable(text: $searchText, prompt: "Search products") {
                // 来自最近搜索的本地建议
                ForEach(matchingRecent, id: \.self) { term in
                    Label(term, systemImage: "clock")
                        .searchCompletion(term)
                }
            }
            .onSubmit(of: .search) {
                // 提交时进行服务器搜索
                Task {
                    searchResults = await ProductAPI.search(searchText)
                }
            }
        }
    }

    var matchingRecent: [String] {
        guard !searchText.isEmpty else { return recentSearches }
        return recentSearches.filter {
            $0.localizedCaseInsensitiveContains(searchText)
        }
    }
}

第五部分:搜索范围(iOS 16+)

添加范围

范围会在搜索字段下方添加一个分段选择器,用于按类别缩小结果:

enum SearchScope: String, CaseIterable {
    case all = "All"
    case recipes = "Recipes"
    case ingredients = "Ingredients"
}

struct ScopedSearchView: View {
    @State private var searchText = ""
    @State private var searchScope: SearchScope = .all

    var body: some View {
        NavigationStack {
            List(filteredResults) { result in
                ResultRow(result: result)
            }
            .navigationTitle("Cookbook")
            .searchable(text: $searchText)
            .searchScopes($searchScope) {
                ForEach(SearchScope.allCases, id: \.self) { scope in
                    Text(scope.rawValue).tag(scope)
                }
            }
        }
    }
}

适用平台:iOS 16+、macOS 13+

范围激活(iOS 16.4+)

控制范围何时出现:

.searchScopes($searchScope, activation: .onTextEntry) {
    // 范围仅在用户开始输入时出现
    ForEach(SearchScope.allCases, id: \.self) { scope in
        Text(scope.rawValue).tag(scope)
    }
}
激活方式行为
.automatic系统默认
.onTextEntry用户输入文本时出现范围
.onSearchPresentation搜索激活时出现范围

平台差异:

  • iOS/iPadOS:范围默认在文本输入时出现,取消时消失
  • macOS:范围在搜索呈现时出现,取消时消失

第六部分:搜索标记(iOS 16+)

标记是结构化的搜索元素,在搜索字段中以“药丸”形式与自由文本一起出现。

基本标记

enum RecipeToken: Identifiable, Hashable {
    case cuisine(String)
    case difficulty(String)

    var id: Self { self }
}

struct TokenSearchView: View {
    @State private var searchText = ""
    @State private var tokens: [RecipeToken] = []

    var body: some View {
        NavigationStack {
            List(filteredRecipes) { recipe in
                RecipeRow(recipe: recipe)
            }
            .navigationTitle("Recipes")
            .searchable(text: $searchText, tokens: $tokens) { token in
                switch token {
                case .cuisine(let name):
                    Label(name, systemImage: "globe")
                case .difficulty(let name):
                    Label(name, systemImage: "star")
                }
            }
        }
    }
}

适用平台:iOS 16+

标记模型要求:每个标记元素必须符合 Identifiable。

建议标记(iOS 17+)

.searchable(
    text: $searchText,
    tokens: $tokens,
    suggestedTokens: $suggestedTokens,
    prompt: "Search recipes"
) { token in
    Label(token.displayName, systemImage: token.icon)
}

适用平台:iOS 17+ 添加了 suggestedTokens 和 isPresented 参数。

结合标记 + 文本过滤

var filteredRecipes: [Recipe] {
    var results = allRecipes

    // 应用标记过滤器
    for token in tokens {
        switch token {
        case .cuisine(let cuisine):
            results = results.filter { $0.cuisine == cuisine }
        case .difficulty(let difficulty):
            results = results.filter { $0.difficulty == difficulty }
        }
    }

    // 应用文本过滤器
    if !searchText.isEmpty {
        results = results.filter {
            $0.name.localizedCaseInsensitiveContains(searchText)
        }
    }

    return results
}

第七部分:编程式搜索控制(iOS 18+)

searchFocused

将一个 FocusState<Bool> 绑定到搜索字段,以编程方式激活或关闭搜索:

struct ProgrammaticSearchView: View {
    @State private var searchText = ""
    @FocusState private var isSearchFocused: Bool

    var body: some View {
        NavigationStack {
            VStack {
                Button("开始搜索") {
                    isSearchFocused = true  // 激活搜索字段
                }

                List(filteredItems) { item in
                    Text(item.name)
                }
            }
            .navigationTitle("项目")
            .searchable(text: $searchText)
            .searchFocused($isSearchFocused)
        }
    }
}

适用平台:iOS 18+、macOS 15+

关键规则:searchFocused 修饰符必须直接放置在应用了 .searchable() 的视图上,或者放置在导航容器上。


第八部分:搜索呈现工具栏行为(iOS 17.1+)

避免隐藏内容

.searchPresentationToolbarBehavior(.avoidHidingContent)

适用平台:iOS 17.1+

当搜索激活时,默认情况下 SwiftUI 可能会隐藏导航栏和工具栏以腾出空间。使用此修饰符可以阻止这种行为,并在搜索时保持工具栏和导航栏可见。

struct PersistentToolbarSearchView: View {
    @State private var searchText = ""

    var body: some View {
        NavigationStack {
            List(items) { item in
                Text(item.name)
            }
            .navigationTitle("项目")
            .toolbar {
                ToolbarItem(placement: .primaryAction) {
                    Button("过滤", systemImage: "line.3.horizontal.decrease.circle") { }
                }
            }
            .searchable(text: $searchText)
            .searchPresentationToolbarBehavior(.avoidHidingContent)  // 搜索时保持工具栏可见
        }
    }
}

常见问题

问题:搜索字段未出现

原因:导航容器缺失。searchable 必须放置在 NavigationStack 或 NavigationSplitView 内部。

修复:将视图包裹在导航容器中。

// 错误:搜索字段不出现
struct MissingSearchView: View {
    @State private var query = ""
    var body: some View {
        List(items) { ... }
            .searchable(text: $query)  // 没有导航容器
    }
}

// 正确
struct FixedSearchView: View {
    @State private var query = ""
    var body: some View {
        NavigationStack {
            List(items) { ... }
                .searchable(text: $query)
        }
    }
}

问题:isSearching 始终为 false

原因:isSearching 从错误的视图层级读取。它必须从附加了 .searchable() 的视图的子视图中读取。

固定:读取 isSearching 的提取子视图:

// 错误
struct BadSearchView: View {
    @State private var query = ""
    @Environment(\.isSearching) private var isSearching  // 始终为 false

    var body: some View {
        NavigationStack {
            List { ... }
                .searchable(text: $query)
        }
    }
}

// 正确
struct GoodSearchView: View {
    @State private var query = ""

    var body: some View {
        NavigationStack {
            SearchContent(query: $query)
                .searchable(text: $query)
        }
    }
}

struct SearchContent: View {
    @Binding var query: String
    @Environment(\.isSearching) private var isSearching  // 现在有效

    var body: some View {
        List { ... }
    }
}

问题:建议不会触发补全

原因:建议视图上缺少 .searchCompletion()。

修复:为每个建议视图添加 .searchCompletion():

.searchable(text: $searchText) {
    ForEach(suggestions) { suggestion in
        Text(suggestion.name)
            .searchCompletion(suggestion.name)  // 这是必须的
    }
}

问题:标记不起作用

原因:标记模型不符合 Identifiable,或者标记视图闭包缺失。

修复:确保你的标记类型符合 Identifiable:

enum SearchToken: Identifiable, Hashable {
    case category(String)
    case author(String)

    var id: Self { self }
}

并在初始化器中提供标记视图:

.searchable(
    text: $searchText,
    tokens: $tokens,
    prompt: "搜索"
) { token in
    switch token {
    case .category(let name):
        Text(name)  // 或其他标记视图
    case .author(let name):
        Label(name, systemImage: "person")
    }
}

平台摘要

特性iOS 15iOS 16iOS 17iOS 18iOS 26
基本 .searchable✅✅✅✅✅
搜索建议✅✅✅✅✅
.onSubmit(of: .search)✅✅✅✅✅
isSearching / dismissSearch✅✅✅✅✅
搜索范围❌✅✅✅✅
搜索标记❌✅✅✅✅
建议标记❌❌✅✅✅
.searchFocused❌❌❌✅✅
.avoidHidingContent❌❌❌✅✅
底部对齐 / .minimize / 搜索标签页❌❌❌❌✅

相关技能

  • swiftui-26-ref - iOS 26 搜索新特性(底部对齐搜索、.searchToolbarBehavior(.minimize)、Tab(role: .search)、DefaultToolbarItem(kind: .search))
  • swiftui-api-patterns - 一般 SwiftUI 模式和最佳实践

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

相关技能