iosswiftuisearchbar

Swift: searchBar - how to change "Cancel" Button title


I have UIViewController which adopted UISearchBarDelegate. And set its delegate to self with: resultSearchController.searchBar.delegate = self. It works fine I tested it with searchBarCancelButtonClicked method%

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        println("Сancel button tapped")
    }

I see "Сancel button tapped" in console. But I would like to change "Cancel" Button title and I don't know how. I tried with:

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {      
        var barButton = UIBarButtonItem(title: "Button Title", style: UIBarButtonItemStyle.Done, target: self, action: "here")
        self.resultSearchController.searchBar.showsCancelButton = false
        self.resultSearchController.navigationItem.rightBarButtonItem = barButton
    }

But it doesn't work. Could you help me please?


Solution

  • func searchDisplayControllerWillBeginSearch(controller: UISearchDisplayController) {
        self.searchDisplayController?.searchBar.showsCancelButton = true
        var cancelButton: UIButton
        var topView: UIView = self.searchDisplayController?.searchBar.subviews[0] as UIView
        for subView in topView.subviews {
            if subView.isKindOfClass(NSClassFromString("UINavigationButton")) {
                cancelButton = subView as UIButton
                cancelButton.setTitle("Vazgeç", forState: UIControlState.Normal)
            }
        }
    }