如何在一个UIBarButtonItem中使用两个函数?

时间:2011-10-28 20:33:15

标签: iphone objective-c

我正在使用iPhone应用中的工具栏。我在工具栏上有一个搜索按钮,一旦你点击我想把它改成完成按钮。我该怎么做?

- (IBAction) openSearch:(id) sender {
   UIBarButtonItem *bbi = (UIBarButtonItem *) sender;
   bool clicked = false;

   if (clicked) {
        // Do something
   }
}

任何帮助?

2 个答案:

答案 0 :(得分:1)

如果您想模仿“完成”按钮的行为,可以在搜索方法中使用以下代码。

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

通过在“true”和“false”之间切换BOOL“clicked”,您将在“Done”和“Bordered”之间更改按钮的样式。您可以在相应条件下执行您想要的任何操作,还可以自定义你想要的按钮也是如此。我希望这会有所帮助。

编辑:

你也可以完全取消BOOL并将条件建立在现有风格的基础上:

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
}

答案 1 :(得分:0)

ViewController.h

@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

ViewController.cpp

@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