显示带动作的搜索栏(条形项)

时间:2016-08-02 19:40:47

标签: ios swift action uisearchbar

我的搜索栏有问题。我需要在右上角创建一个带有搜索按钮的表格视图,当我点击它时,它应该显示搜索栏。

我的代码在这里:

// Search controller
searchController = ({
    let controller = UISearchController(searchResultsController: nil)
    controller.delegate = self
    controller.searchBar.delegate = self
    controller.searchResultsUpdater = self
    controller.dimsBackgroundDuringPresentation = false         
    controller.hidesNavigationBarDuringPresentation = true
    controller.searchBar.sizeToFit()
    return controller
})()

这是行动:

// Search action
@IBAction func search(sender: UIBarButtonItem) {
    print("Open search")
    searchController.active = true
    if searchController.searchBar.isFirstResponder() == false {
        searchController.searchBar.becomeFirstResponder()
    }
}

当我点击按钮时,没有任何反应(仅在控制台中打印文本),我想要的是在下图中:

Show search

2 个答案:

答案 0 :(得分:13)

你的班级需要符合UISearchBarDelegate,我不确定你是否已经这样做了。还要确保显示搜索视图

来自Apple的文档:

  

UISearchBarDelegate协议定义了为实现UISearchBar控制功能而实现的可选方法。 UISearchBar对象为条形图上的搜索字段提供用户界面,但应用程序负责在按下按钮时实现操作。在文本字段中输入文本时,代表至少需要执行实际搜索。

以下是我的应用

中的示例
@IBAction func searchAction(sender: UIBarButtonItem) {
    // Create the search controller and specify that it should present its results in this same view        
    searchController = UISearchController(searchResultsController: nil) 

    // Set any properties (in this case, don't hide the nav bar and don't show the emoji keyboard option)
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.searchBar.keyboardType = UIKeyboardType.ASCIICapable

    // Make this class the delegate and present the search
    self.searchController.searchBar.delegate = self
    presentViewController(searchController, animated: true, completion: nil)
}

答案 1 :(得分:0)

旧问题,但想添加一个新答案(也许自2016年的原始答案以来情况有所改变。)

假设您已经设置了搜索控制器,只需在视图控制器上调用它即可。无需遵循UISearchBarDelegate:

快速5

present(searchController, animated: true, completion: nil)