0
votes

I have been struggling with change of text on Cancel button in iOS7.

In iOS6 I have no problem -- the text is changed. But in iOS7 it has no effect and I am stuck with "cancel".

But finally I found the code below which changes the default "cancel" text in iOS7.

The problem now is that running in iOS6 the app crashes when opening the search bar.

Does anybody know why and how to fix this to work both on iOS7 and iOS6? This is the error message.

2013-11-10 16:58:38.048 Testapp[45017:907] -[__NSCFConstantString setTitle:forState:]: unrecognized selector sent to instance 0x11dfc 2013-11-10 16:58:38.050 Testapp[45017:907] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString setTitle:forState:]: unrecognized selector sent to instance 0x11dfc'

And the main.m

int retVal = UIApplicationMain(argc, argv, nil, nil);

gets a Thread 1:signal SIGABRT

The code is as below.

-(void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller{
    self.searchDisplayController.searchBar.showsCancelButton = YES;
    UIButton *cancelButton;
    UIView *topView = self.searchDisplayController.searchBar.subviews[0];
    for (UIView *subView in topView.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
            cancelButton = (UIButton*)subView;
        }
  }
    if (cancelButton) {
                [cancelButton setTitle:@"Testing" forState:UIControlStateNormal];
    }
}
1
When ever you post a question about a crash, you must include details about the crash. What is the full error message? Which line of code causes the crash?rmaddy
You should at least initialize cancelButton to nil where you declare it. That should avoid the crash though it won't solve your main problem.user467105
Please check button connection.Abha

1 Answers

1
votes

In IOS7 Apple wrapped searchBar subviews into one additional view. Here's pseudocode how you can changed title on both IOS versions:

if ( iosVersion < IOS7) {
    subViews = self.searchBar.subviews;
} else {
    subViews = [(self.searchBar.subviews[0]) subviews];
}

for (id view in subViews) {
    if ([view isKindOfClass:[UIButton class]]) {
        UIButton* cancelbutton = (UIButton* )view;
        [cancelbutton setTitle:@"NewTitle" forState:UIControlStateNormal];
        break;
    }
}