Reputation: 1253
I have implemented search bar in my app with custom(localized) title.
for the first time when I tap on search it shows cancel button as follow:
First Time
Second Time When I press cancel button & again tap on Search Bar, it looks fine.
My code
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:YES animated:YES];
UIButton *cancelButton;
UIView *topView = search.subviews[0];
for (UIView *subView in topView.subviews) {
if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
cancelButton = (UIButton*)subView;
}
}
if (cancelButton) {
[cancelButton setTitle:Localized(@"Cancel") forState:UIControlStateNormal];
}
}
Upvotes: 0
Views: 1406
Reputation: 7117
Try setting your NSLocalizedString
with UIAppearance
:
[[UIButton appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:Localized(@"Cancel") forState:UIControlStateNormal];
swift
UIButton.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitle("v1_cancel", for: .normal)
(which no longer works in modern ios) this one Change UISearchBar cancel button text in iOS 8 is up to date
Upvotes: 2
Reputation: 387
I had translate the Jasper answer in swift 4:
UIButton.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitle("Cancel", for: .normal)
Upvotes: 0
Reputation: 10479
It's working for me:
if (cancelButton) {
[cancelButton setTitle:Localized(@"Cancel") forState:UIControlStateNormal];
[search setNeedsLayout];
[search layoutIfNeeded];
}
Upvotes: 2