使用没有故事板的UISearchController

Big*_*zzy 2 uitableview ios uisearchcontroller

我相对较新的iOS(100小时左右),我正在尝试实现一个没有故事板的UISearchController.是否可以通过编程方式执行此操作?

Pra*_*I V 13

您必须以UISearchController编程方式实现,因为Apple尚未提供使用Storyboard进行设置的功能.

以下是UISearchController在视图控制器中实现的步骤

  • 符合UISearchResultsUpdating协议
  • 创建一个变量来引用 UISearchController

    var searchController: UISearchController!
    
    Run Code Online (Sandbox Code Playgroud)
  • 设置searchController在viewDidLoad(_:)

    override func viewDidLoad() {
        super.viewDidLoad()
    
        searchController = UISearchController(searchResultsController: nil)
    
        // The object responsible for updating the contents of the search results controller.
        searchController.searchResultsUpdater = self
    
        // Determines whether the underlying content is dimmed during a search.
        // if we are presenting the display results in the same view, this should be false
        searchController.dimsBackgroundDuringPresentation = false
    
        // Make sure the that the search bar is visible within the navigation bar.
        searchController.searchBar.sizeToFit()
    
        // Include the search controller's search bar within the table's header view.
        tableView.tableHeaderView = searchController.searchBar
    
        definesPresentationContext = true
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 实现方法updateSearchResultsForSearchController(_:),当搜索栏成为第一个响应者或用户对搜索栏内的文本进行更改时调用该方法

    func updateSearchResultsForSearchController(searchController: UISearchController) {
        // No need to update anything if we're being dismissed.
        if !searchController.active {
            return
        }
    
        // you can access the text in the search bar as below
        filterString = searchController.searchBar.text
    
        // write some code to filter the data provided to your tableview
    }
    
    Run Code Online (Sandbox Code Playgroud)