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

Nik*_*ola 5 action uisearchbar ios swift

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

我的代码在这里:

// 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
})()
Run Code Online (Sandbox Code Playgroud)

这是行动:

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

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

显示搜索

Jas*_*son 14

你的类需要符合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)
}
Run Code Online (Sandbox Code Playgroud)

  • 请不要在答案中添加“ searchController.searchBar.keyboardType = UIKeyboardType.ASCIICapable”,因为键盘对其他语言(仅数字和特殊符号)无效。您为什么还要在此答案中添加它? (2认同)

Sea*_* Li 6

老问题,但想添加一个新答案(也许自 2016 年的原始答案以来情况发生了变化)。

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

雨燕5

present(searchController, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)