Reputation: 2025
I'm using the toolbar in my iPhone app. I have a search button on the toolbar, once you click I want to change it to done button. How do I do this?
- (IBAction) openSearch:(id) sender {
UIBarButtonItem *bbi = (UIBarButtonItem *) sender;
bool clicked = false;
if (clicked) {
// Do something
}
}
Any help?
Upvotes: 1
Views: 275
Reputation: 229
If you would like to mimic behavior of a "done" button you could use the following code within your search method.
if( clicked ){
//This will change your Bar Button Item to a blue "done" button.
[bbi setStyle:UIBarButtonItemStyleDone];
[bbi setTitle:@"Done"];
}else{
//This will change the style of your Bar Button Item back to grey.
[bbi setStyle:UIBarButtonItemStyleBordered];
[bbi setTitle:@"Search"];
}
By toggling the BOOL "clicked" between true and false, you'll change the style of the button between "Done" and "Bordered. You can perform whatever operations you would like within the respective conditions, and you can also customize the buttons however you want to as well. I hope this helps.
EDIT:
You could also do away with the BOOL entirely and base the condition on the existing style:
if( bbi.style == UIBarButtonItemStyleBordered ){
[bbi setStyle:UIBarButtonItemStyleDone];
[bbi setTitle:@"Done"];
//Do stuff when 'search' is pressed
}else{
[bbi setStyle:UIBarButtonItemStyleBordered];
[bbi setTitle:@"Search"];
//Do stuff when 'done' is pressed
}
Upvotes: 1
Reputation: 385890
@interface ViewController : UIViewController
@property BOOL isSearching;
@property (strong) IBOutlet UIBarButtonItem *button; // connect to the Search/Done button in your XIB
- (IBAction)buttonClicked:(id)sender; // Connect this as the button's action in your XIB
@end
@implementation ViewController
@synthesize button = _button;
@synthesize isSearching = _isSearching;
- (void)setSearchButtonTitle
{
self.button.title = self.isSearching ? @"Done" : @"Search";
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.button.possibleTitles = [NSSet setWithObjects:@"Done", @"Search", nil];
[self setSearchButtonTitle];
}
- (IBAction)buttonClicked:(id)sender
{
self.isSearching = !self.isSearching;
[self setSearchButtonTitle];
}
@end
Upvotes: 0