UISearchController setActive 什么都不做

UISearchController setActive does nothing

我试图通过设置其 isActive 属性 来显示搜索控制器以响应按钮,但它没有出现。

lazy var searchController: UISeachController = {
    let searchController = UISearchController(searchResultsController: nil)
    searchController.delegate = self
    return searchController
}()

override func viewDidLoad() {
    super.viewDidLoad()
    definesPresentationContext = true
}

// Called when a button on the navbar is tapped
@obcj private func searchTapped() {
    // The doc says you can force the search controller to appear by setting isActive,
    // but nothing happens
    searchController.isActive = true

    // Calling present does show it, but the search bar appears behind the navbar. 
    // And the delegate methods are still not called
    //present(searchController, animated: true)
}

func willPresentSearchController(_ searchController: UISearchController) {
    // Not called, even when calling 'present'
}

似乎isActive 仅当搜索栏位于视图层次结构中时才有效。

// This will place the search bar in the title view, allowing you to
// have other buttons on the right of the search bar.
navigationItem.titleView = searchController.searchBar

或者

// This takes up a whole other row under title row.
navigationItem.searchController = searchController

但是如果你走这条路,你不需要自己设置 isActive - 当用户与搜索栏交互时,搜索控制器会自动出现。我仍然不明白应该如何使用 isActive,但它确实回答了最初的问题。