使用没有故事板的UISearchController

时间:2015-03-26 17:28:08

标签: ios uitableview uisearchcontroller

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

2 个答案:

答案 0 :(得分:12)

您必须以编程方式实施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
    }
    

答案 1 :(得分:0)

除了Praveen的详细答案之外,如果您需要Objective-C示例,Apple提供了example code来处理iOS 8中的UISearchController。