searchBarSearchButtonClicked无效

时间:2018-03-19 23:36:37

标签: ios swift uisearchbar

我已经在viewDidLoad()方法中设置了委托,并且还检查了IB以查看委托是否在使用(控制+拖动)时显示,并且它实际上显示为连接。我也删除了它,并在IB中完全添加了一个新的SearchBar并将其重新连接起来。似乎没有什么可以做到的。有什么建议?

override func viewDidLoad() {
    self.searchBar.layer.zPosition = 1
    self.searchBar.delegate = self
}

//this is never being called, breakpoint never hits
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    print("searchText \(searchText)")
}

//this is never being called, breakpoint never hits
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    print("search button clicked")
    self.firebaseQuery()
}

4 个答案:

答案 0 :(得分:1)

您的自定义View Controller类是否在Interface Builder中设置?即在Identity Inspector选项卡上,确保在Custom Class部分中设置了所需的UIViewController子类。

另外,尝试在viewDidLoad()中设置断点。运行应用程序,如果断点没有达到预期的目的,那么这有助于缩小问题范围。

答案 1 :(得分:0)

https://www.reddit.com/r/swift/comments/85o75h/bug_uisearchbar_delegate_methods_not_being_called/dvzcbb4/

感谢reddit用户@applishish我遇到了问题

我没有在参数-_-

前加下划线

感谢大家的帮助!

答案 2 :(得分:0)

您是否可能错误地设置了委托?

在Interface Builder中,按住Command键并单击搜索栏,将委托拖动到故事板中的黄色ViewController按钮以设置委托。 从self.searchBar.delegate = self

中删除viewDidLoad()

Set ViewController as UISearchBarDelegate Xcode 9.4 beta

我也没看到你的viewController类是否已经正确地符合UISearchBarDelegate我会将它添加到你的控制器的扩展中,并把你所有的代码都放在那里。

 class ViewController: UIViewController{...}


 extension ViewController: UISearchBarDelegate {
     // implement all searchBar related methods here: 

    func searchBarButtonClicked(_ searchBar: UISearchBar) {
       //capture the string 
       if let input = searchBar.text {
        // do something with string.  
        print(input)


       }


 }

答案 3 :(得分:0)

当我使用IB进行设置时,我也遇到了问题。我最后使用代码而不是IB来设置它,并且它有效。试试这种方式:

    class MySearchTableViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {

        let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()

        self.searchController.searchBar.autocapitalizationType = UITextAutocapitalizationType.none
        self.navigationItem.searchController = self.searchController

        //if this is set to true, the search bar hides when you scroll.
        self.navigationItem.hidesSearchBarWhenScrolling = false

        //this is so I'm told of changes to what's typed
        self.searchController.searchResultsUpdater = self

        self.searchController.searchBar.delegate = self
}

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {            
        //hopefully this gets called when you click Search button
}

    func updateSearchResults(for searchController: UISearchController) {
        //if you want to start searching on each keystroke, you implement this method. I'm going to wait until they click Search.
    }