我对 iOS 比较陌生(100 小时左右),我正在尝试实现一个没有情节提要的 UISearchController。是否可以以编程方式执行此操作?
问问题
5240 次
1 回答
15
您必须以UISearchController
编程方式实现,因为 Apple 尚未提供使用 Storyboard 进行设置的功能。
以下是UISearchController
在视图控制器中实现的步骤
- 符合
UISearchResultsUpdating
协议 创建一个变量来引用
UISearchController
var searchController: UISearchController!
设置
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 }
实现该方法
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 }
于 2015-03-27T20:39:13.900 回答