首页 > 解决方案 > 如何显示搜索结果,如 iOS“联系人”应用

问题描述

我是新的 iOS 编程。我试图实现我的应用程序看起来像 iOS 联系人应用程序。但我不知道如何实现我想要的。我想让搜索结果看起来像默认的 iOS 应用程序。

看看我到目前为止的尝试:

当我输入一些东西时, dimsBackgroundDuringPresentation 仍然 <code>true</code>

当我输入一些东西时, dimsBackgroundDuringPresentation 仍然是true

这是我的期望:

这是我期望的细节

我想知道这个应用程序如何显示这样的结果。

这是我声明的方式UISearchController

lazy var searchController: UISearchController = ({

    let controller = UISearchController(searchResultsController: nil)

    controller.hidesNavigationBarDuringPresentation = false
    controller.searchBar.sizeToFit()
    controller.searchBar.backgroundColor = UIColor.clear
    controller.searchBar.placeholder = "Search"
    controller.dimsBackgroundDuringPresentation = true

    return controller

})()

这是我如何初始化searchBar到标题部分的tableView

let searchBar = searchController.searchBar
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
    searchBar.delegate = self

    tableView.tableHeaderView = searchController.searchBar

这是委托的功能UISearchResultsUpdating

func updateSearchResults(for searchController: UISearchController) {
    if let count = searchController.searchBar.text?.count {
        if count > 0  {

            filterArray.removeAll(keepingCapacity: false)
            var a = [String]()
            a = [searchController.searchBar.text!]
            filterArray = a
            searchController.dimsBackgroundDuringPresentation = false
            tableView.reloadData()
        }else {
            searchController.dimsBackgroundDuringPresentation = true
            filterArray.removeAll(keepingCapacity: false)
            filterArray = array
            tableView.reloadData()
        }
    }

}

这是我的tableView手机的样子

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if searchController.isActive {
        return filterArray.count
    }else {
        return array.count
    }

}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

    if searchController.isActive {
        cell.textLabel?.text = filterArray[indexPath.row]
    }else {
        cell.textLabel?.text = array[indexPath.row]
    }


    return cell

}

标签: iosswiftuitableviewuisearchbar

解决方案


尝试以下选项:

let search = UISearchController(searchResultsController: nil)
            self.definesPresentationContext = true
            search.dimsBackgroundDuringPresentation = false
            navigationItem.searchController = search
            navigationItem.hidesSearchBarWhenScrolling = false

尝试我的 repo 中的代码以查看它是否正常工作,只需点击一个 tableview 项目,它将转到第二个控制器,您可以在其中看到搜索栏并点击它以查看这是否是您想要的

github链接


推荐阅读