tags:

views:

255

answers:

2

HI I am developing an Application where i wanted to change the text of Search String in the SearchBar. I wanted to change the text of Cancel Button Also which appears next to the SearchBar. Before entering any string in the search bar we wil get the Search String as the default string. i wanted to change the text of that string and when we click on that searchbar we get a cancel button next to searchbar and i wanted to change the text of that cancel button. PLease help me.

+2  A: 

If by "Search String", you mean the placeholder, then this should do it:

[searchBar setPlaceholder:@"Whatever you want"];

As for changing the text of the cancel button, that may be a bit more difficult. Apple does not use a standard UIBarButtonItem for this, or even a non-standard UIButton. Instead they use a UINavigationButton for the cancel button in the search bar. Since this is not a documented public class, attempting to modify it could very well get your app rejected from the App Store. If you do want to risk rejection, then you could search through the subviews of searchBar:

for(UIView *view in [searchBar subviews]) {
    if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
        [(UIBarItem *)view setTitle:@"Whatever you want"];
    }
}

Note that the cancel button is loaded lazily, so you will have to do this modification when the search bar is activated by the user.

glorifiedHacker
Changing the text of the search field works but not the text of cancel button...
Pradeep Reddy Kypa
It won't work until after the search bar is activated. Like I mentioned above, the cancel button is loaded lazily, so it doesn't exist until after the search field is tapped. You can use the delegate methods for UISearchDisplayController to get around this problem.
glorifiedHacker
Note: you don't have to call -class on a Class object from NSClassFromString, only from classes you reference by name alone.
chpwn
You're right... I originally had [UINavigationButton class] in my code for testing, but since this would risk App Store rejection, I substituted the NSClassFromString() call and forgot to remove the class message.
glorifiedHacker
+1  A: 

You also need to have the "searchBar setShowsCancelButton" before the procedure.

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller {
[theSearchBar setShowsCancelButton:YES animated:NO];
for(UIView *subView in theSearchBar.subviews){
    if([subView isKindOfClass:UIButton.class]){
        [(UIButton*)subView setTitle:@"Done" forState:UIControlStateNormal];
    }
}

}

Note also: use UIButton to avoid problems with Apple!

David Brownstone
UIButton.class is an invalid use of the dot syntax, use [UIButton class].
chpwn
Absolutely correct - [UIButton class] is better syntax!
David Brownstone