简体   繁体   English

点击搜索按钮后,在搜索栏中激活取消按钮

[英]Make Cancel button in search bar active after search button tapped

I have search bar and cancel button, after search button tapped, it display the result but cancel button is inactive and i need to click twice to make it work and back to the initial result. 我有搜索栏和取消按钮,点击搜索按钮后,显示结果但取消按钮无效,我需要点击两次才能使其工作并返回初始结果。 How to make cancel button active after the search result appear? 如何在搜索结果出现后激活取消按钮?

here's my code 这是我的代码

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    searchBar.endEditing(true)
    searchBar.setShowsCancelButton(true, animated: true)
    filterContentForSearchText(searchBar.text!, scope: "All")
    print(searchBar.text)
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    searchBar.text = ""
    searchBar.resignFirstResponder()
    searchBar.setShowsCancelButton(false, animated: true)
    database = dataUtuh
    self.collectionView.reloadData()
}

I already implement UISearchBarDelegate and searchBar.delegate = self on my viewDidLoad 我已经在viewDidLoad上实现了UISearchBarDelegatesearchBar.delegate = self

Put the code to enable the cancel button in search bar's searchBarSearchButtonClicked delegate method In this way after the search bar will be clicked the cancel button will be still enabled. 将代码设置为在搜索栏的searchBarSearchButtonClicked委托方法中启用取消按钮这样,在单击搜索栏后,仍将启用取消按钮。

so the complete code snippet would be 所以完整的代码片段将是

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    searchBar.endEditing(true)
    searchBar.setShowsCancelButton(true, animated: true)
    print(searchBar.text)


    for view in searchBar.subviews {
        for subview in view.subviews {
            if let button = subview as? UIButton {
                button.enabled = true
            }
        }
    }

}

Happy coding... 快乐的编码......

In my experience if you do searchBar.endEditing(true) then the cancel button is disabled, try adding this after that to see if its work, im also using it in my project: 根据我的经验,如果你执行searchBar.endEditing(true)那么取消按钮被禁用,尝试在此之后添加它以查看它是否正常工作,我也在我的项目中使用它:

func enableCancelButton (searchBar : UISearchBar) {
    for view1 in searchBar.subviews {
        for view2 in view1.subviews {
            if view2.isKindOfClass(UIButton) {
                let button = view2 as! UIButton
                button.enabled = true
                button.userInteractionEnabled = true
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM