Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 702
Ariel Gemilang Avatar asked Jan 06 '23 10:01

Ariel Gemilang


1 Answers

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.

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...

like image 68
Andolasoft Avatar answered Jan 13 '23 10:01

Andolasoft