You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI searchable功能失效,输入搜索词仍显示全部内容求排查

SwiftUI Searchable功能失效问题修复

核心问题排查

你的代码存在两个直接导致搜索失效的问题:

  • 变量名不匹配:声明的@State变量是search,但searchResults计算属性里判断的是未定义的searchText.isEmpty,导致永远返回完整的游戏列表,不会执行过滤逻辑。
  • 大小写匹配漏洞:当前仅将搜索文本转小写,但未处理游戏名称的大小写,导致名称为大写的游戏无法被小写搜索词匹配到。

修复后的完整代码

@State var search = ""

var searchResults: [Game] {
    if search.isEmpty { // 修正为使用正确的search变量
        return gameList.games
    } else {
        let lowercasedSearch = search.lowercased()
        // 将游戏名称也转小写,实现大小写不敏感匹配
        return gameList.games.filter { $0.name.lowercased().contains(lowercasedSearch) }
    }
}

init() {
    self.gameList.reload()
}

var body: some View {
    let columns = [
        GridItem(.adaptive(minimum: 150))
    ]
    NavigationView {
        if gameList.isLoading {
            FourSquares()
        } else {
            ScrollView {
                LazyVGrid(columns: columns, spacing: 20) {
                    ForEach(searchResults) { game in
                        NavigationLink(destination: GameDetailView(gameId: game.id)) {
                            GameRowView(game: game)
                        }
                    }
                }
                .padding(.horizontal)
                .padding(.vertical, 5)
                .onAppear {
                    UITableView.appearance().separatorStyle = .none
                }
                .id(UUID())
            }
            .navigationBarTitle("Upcoming Games", displayMode: .automatic)
        }
    }
    .environmentObject(favorites)
    .searchable(text: $search)
    .refreshable { self.gameList.reload() }
    .navigationViewStyle(StackNavigationViewStyle())
}

额外注意事项

  • 确保Game类型已遵循Identifiable协议,否则ForEach会出现编译错误。
  • 若gameList是异步加载数据的ObservableObject,需确保games属性使用@Published修饰,这样数据更新时searchResults会自动刷新。

内容的提问来源于stack exchange,提问作者Yousef Abu Sallamah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:45:38