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
相关产品推荐
相关产品推荐

