【问题标题】:Show search bar with action (bar item)显示带有操作的搜索栏(栏项)
【发布时间】:2016-08-02 19:40:47
【问题描述】:

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

我的代码在这里:

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

当我点击按钮时,什么也没有发生(仅在控制台中打印文本),我想要的是下图:

【问题讨论】:

    标签: ios swift action uisearchbar


    【解决方案1】:

    您的班级需要符合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)
    }
    

    【讨论】:

    • 请不要在您的答案中添加searchController.searchBar.keyboardType = UIKeyboardType.ASCIICapable,因为键盘对其他语言无用(仅数字和特殊符号)。你为什么还要在这个答案中添加它?
    【解决方案2】:

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

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

    斯威夫特 5

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      • 1970-01-01
      • 2017-12-28
      • 2014-11-29
      相关资源
      最近更新 更多