Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 789
user3742622 Avatar asked Apr 04 '15 11:04

user3742622


2 Answers

Try accessing the button text using setValue, like this:

Swift 4

searchController.searchBar.setValue("New Title", forKey: "cancelButtonText")

it works for me :)

like image 110
GabrielaBezerra Avatar answered Sep 28 '22 03:09

GabrielaBezerra


Put this in the viewDidLoad() of the view controller after initialising your search controller.

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "your button title"
like image 31
Arun Kumar Avatar answered Sep 28 '22 03:09

Arun Kumar