I wish to change the title of the cancel button in iOS. I have been using this previously:
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayCon
Refer to @Salih's solution above, I used this code and work perfect! Just call the method setupAppearance in AppDelegate.m when app launching.
- (void)setupAppearance
{
id appearance = nil;
if (IOS9_OR_LATER) {
appearance = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]];
} else {
appearance = [UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil];
}
[appearance setTitle:@"CANCEL"];
}
For Swift 3.0
This is working fine.
func setSearchButtonText(text:String,searchBar:UISearchBar) {
for subview in searchBar.subviews {
for innerSubViews in subview.subviews {
if let cancelButton = innerSubViews as? UIButton {
cancelButton.setTitleColor(UIColor.white, for: .normal)
cancelButton.setTitle(text, for: .normal)
}
}
}
}
And call the method
setSearchButtonText(text: "Done", searchBar: yourSearchBar)
Here is the output
Chiming in with the code I used inside the UIKitUISearchResultsUpdating
protocol method updateSearchResults(for searchController: UISearchController)
:
if let cancelButton : UIButton = searchController.searchBar.value(forKey: "_cancelButton") as? UIButton {
cancelButton.setTitle("Back", for: UIControlState.normal)
}
(iOS 10, Swift 3.0)
If you just want to change the "Cancel" text to the same in your locale, the proper way I think is using localization. Here is how:
en.lproj
directory(not sure this is necessary) edit your Info.plist
and add these lines:
Localization native development region
: your region (for example: en
)Localizations
: for example English
Note: it does not work in Simulator, test it on the device!
(Source: http://www.ibabbleon.com/iphone_app_localization.html)
Put this line in appDelegate
[[UIButton appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:@"Your Title" forState:UIControlStateNormal];
It seems like "self.searchDisplayController.searchBar.subviews" just return the "searchBar" itself. I tried bellow, and it works!
for (UIView *searBarView in [self.searchDisplayController.searchBar subviews])
{
for (UIView *subView in [searBarView subviews])
{
if ([subView isKindOfClass:[UIButton class]])
{
UIButton *cancleButton = (UIButton *)subView;
[cancleButton setTitle:@"hi" forState:UIControlStateNormal];
}
}
}