user2526811
user2526811

Reputation: 1253

Cancel Button in UISearchBar issue

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

}

Upvotes: 0

Views: 1406

Answers (3)

Jasper
Jasper

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

Iosif
Iosif

Reputation: 387

I had translate the Jasper answer in swift 4:

UIButton.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitle("Cancel", for: .normal)

Upvotes: 0

Bannings
Bannings

Reputation: 10479

It's working for me:

if (cancelButton) {
    [cancelButton setTitle:Localized(@"Cancel") forState:UIControlStateNormal];
    [search setNeedsLayout];
    [search layoutIfNeeded];
}

Upvotes: 2

Related Questions