0

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

enter image description here

Second Time When I press cancel button & again tap on Search Bar, it looks fine.

enter image description here

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];
    }

}
Nik
  • 1,679
  • 1
  • 20
  • 36
user2526811
  • 1,233
  • 4
  • 20
  • 54

3 Answers3

2

It's working for me:

if (cancelButton) {
    [cancelButton setTitle:Localized(@"Cancel") forState:UIControlStateNormal];
    [search setNeedsLayout];
    [search layoutIfNeeded];
}
Bannings
  • 10,376
  • 7
  • 44
  • 54
2

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

Anton Tropashko
  • 5,486
  • 5
  • 41
  • 66
Jasper
  • 7,031
  • 3
  • 35
  • 43
0

I had translate the Jasper answer in swift 4:

UIButton.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitle("Cancel", for: .normal)
Iosif
  • 353
  • 2
  • 15