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

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

我的代码在这里:

// 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() } } 

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

显示搜索

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

来自Apple的文档:

UISearchBarDelegate协议定义了为实现UISearchBar控制function而实现的可选方法。 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) }