Swift开发中UITableView无法显示更新UISearchBar地址搜索结果
问题根因
- UISearchResultsUpdating协议方法不匹配:你写了两个更新回调方法,带搜索逻辑的
updateSearchResultsForSearchController是iOS 8时代的旧方法,现行系统只会调用updateSearchResults(for:),而你这个正确的方法是空实现,所以搜索请求完全没触发。 - UITableView代理/数据源方法签名错误:
cellForRowAtIndexPath、didSelectRowAtIndexPath都是旧版Swift的方法签名,系统无法识别,就算拿到搜索结果也不会渲染表格、响应点击。 - 主视图控制器
viewDidLoad中存在无效赋值:在resultSearchController初始化之前就给它的searchResultsUpdater赋值,完全不生效。
修复步骤
1. 修复LocationSearchTable的UISearchResultsUpdating实现
删除原来的两个更新回调方法,合并为正确的实现:
extension LocationSearchTable : UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { searchController.showsSearchResultsController = true guard let mapView = mapView, let searchBarText = searchController.searchBar.text else { return } let request = MKLocalSearch.Request() request.naturalLanguageQuery = searchBarText request.region = mapView.region let search = MKLocalSearch(request: request) search.start { response, _ in guard let response = response else { return } self.matchingItems = response.mapItems self.tableView.reloadData() } } }
2. 修复LocationSearchTable的TableView数据源/代理方法签名
替换原有旧签名的数据源、点击事件方法:
extension LocationSearchTable { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return matchingItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! let selectedItem = matchingItems[indexPath.row].placemark cell.textLabel?.text = selectedItem.name cell.detailTextLabel?.text = "" return cell } } extension LocationSearchTable { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedItem = matchingItems[indexPath.row].placemark handleMapSearchDelegate?.dropPinZoomIn(placemark: selectedItem) dismiss(animated: true, completion: nil) } }
3. 清理主视图控制器无效代码
删除locationViewController中viewDidLoad方法里resultSearchController初始化之前的无效赋值行resultSearchController?.searchResultsUpdater = self,同时主控制器不需要遵守UISearchResultsUpdating协议,可以删掉类声明中的该协议,以及对应的空实现func updateSearchResults(for searchController: UISearchController)方法。
内容的提问来源于stack exchange,提问作者Developer Wes
相关产品推荐
相关产品推荐

