Change UISearchBar cancel button text in iOS 8

2019-01-31 12:17发布

I'd like to change the text from ¨Cancel¨to ¨Done¨ of the Cancel button inside the UISearchBar in iOS 8. I am using UISearchController. I've tried different approaches for iOS 6 and iOS 7 and they do not work. Has anybody done this?

12条回答
叼着烟拽天下
2楼-- · 2019-01-31 12:36

Objective-C:

[searchBar setValue:@"customString" forKey:@"_cancelButtonText"];

Swift:

searchBar.setValue("customString", forKey:"_cancelButtonText")
查看更多
SAY GOODBYE
3楼-- · 2019-01-31 12:37

Swift 3.0:

In your AppDelegate add this:

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "my text"
查看更多
虎瘦雄心在
4楼-- · 2019-01-31 12:38

I was having trouble getting this to work for a UISearchBar within a UISearchController. The text didn't change the first time the cancel button was shown but it did the second time.

That is until I saw @polo987's answer. Here's what I did that worked:

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "Done"
查看更多
Lonely孤独者°
5楼-- · 2019-01-31 12:38

I know this may seem to be a bit irrelevant but in my opinion this is safer than using private apis and more efficient than taking a dive into the unknown views. This solution makes sense only if you have your own localisation engine and you do want Apple to follow your mechanism all over the app. Basically my idea is to switch the language the iOS SDK uses to localise the button by altering the "AppleLanguages" key in the NSUserDefaults. You can go here for more information about how this works.

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", @"fr", nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];

Put this code to use the English localisation and a French fallback no matter what language is set on the phone. This only takes effect within the app.

查看更多
对你真心纯属浪费
6楼-- · 2019-01-31 12:42

In Swift4

Change Title:

(searchBar.value(forKey: "cancelButton") as! UIButton).setTitle("Done", for: .normal)

Change Color:

(searchBar.value(forKey: "cancelButton") as! UIButton).setTitleColor(UIColor.blue, for: .normal)

查看更多
一夜七次
7楼-- · 2019-01-31 12:42

Here is Swift solution:

for (view) in _searchController.searchBar.subviews {
    for (subview) in view.subviews {
        if (subview.isKindOfClass(UIButton.self)) {
            let cancelButton = subview as! UIButton
            cancelButton.setTitle("BlaBla", forState: .Normal)
            break
        }
    }
}
查看更多
登录 后发表回答