首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

当UISearchBar为空时,UISearchController结果TableViewController不会清除结果

基础概念

UISearchController 是 iOS 开发中用于实现搜索功能的控件,它通常与 UISearchBarUITableViewController 结合使用。UISearchBar 用于输入搜索关键词,UITableViewController 用于显示搜索结果。

问题描述

UISearchBar 为空时,UISearchController 结果 TableViewController 不会清除结果。

原因分析

这个问题通常是因为 UISearchControlleractive 属性没有正确处理,或者 UISearchResultsUpdating 协议的方法没有正确实现。

解决方法

  1. 确保 UISearchControlleractive 属性正确处理: 当 UISearchBar 的文本为空时,应该将 UISearchControlleractive 属性设置为 false,以清除搜索结果。
  2. 实现 UISearchResultsUpdating 协议的方法: 确保在 updateSearchResults(for:) 方法中正确处理搜索结果的更新。

示例代码

代码语言:txt
复制
import UIKit

class ViewController: UIViewController, UISearchResultsUpdating {

    var searchController: UISearchController!

    override func viewDidLoad() {
        super.viewDidLoad()

        let resultsTableViewController = UITableViewController(style: .plain)
        resultsTableViewController.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

        searchController = UISearchController(searchResultsController: resultsTableViewController)
        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search items"
        navigationItem.searchController = searchController
        definesPresentationContext = true
    }

    // MARK: - UISearchResultsUpdating

    func updateSearchResults(for searchController: UISearchController) {
        let searchBar = searchController.searchBar
        let tableView = searchController.searchResultsController?.tableView

        if searchBar.text?.isEmpty == true {
            tableView?.reloadData()
        } else {
            // Perform your search here and update the table view
            // For example:
            let searchResults = performSearch(with: searchBar.text ?? "")
            (searchController.searchResultsController as? UITableViewController)?.tableView.reloadData()
        }
    }

    func performSearch(with searchText: String) -> [String] {
        // Implement your search logic here
        return []
    }
}

参考链接

通过上述方法,可以确保当 UISearchBar 为空时,UISearchController 结果 TableViewController 能够正确清除搜索结果。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

自定义UISearchController的外观

以前我们在项目中使用搜索框的时候,如果用系统自带的控件则是使用UISearchDisplayController,而自从iOS8之后,系统重新给我们提供了一个搜索控件:UISearchController。在UISearchController中我们无需再自己初始化UISearchBar,只需要提供searchResult展示的视图。然而在开发中,我们往往需要根据项目的风格来改变UISearchBar的外观,通过继承的方式,我们可以完全定制符合项目风格的外观,然而有些情况下我们很难短时间内完成全部的外观定制工作,譬如我们项目用的好几个旧框架,代码中充斥着各种写好的UISearchBar的展示,而改动底层框架并不是一个较好地实践。于是我开始搜索并总结出了几个不通过继承的方式来更改UISearchBar外观的方法。

02
  • 领券