Ariel Gemilang Ariel Gemilang - 2 months ago 35
iOS Question

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

Answer

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:

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
            }
        }
    }
}
Comments