Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

iphone - Add a custom selector to a UIBarButtonItem

I am an iOS newbie. I have a navigation bar button which when clicked should execute a function of my own. What is the best way to do that?

UIBarButtonItem *doneBarButtonItem=[[UIBarButtonItem alloc] init];
doneBarButtonItem.title=@"Done";
self.navigationItem.rightBarButtonItem = doneBarButtonItem;
[doneBarButtonItem release];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One way is to init with the target and action:

UIBarButtonItem *buttonHello = [[UIBarButtonItem alloc] initWithTitle:@"Say Hello"     
    style:UIBarButtonItemStyleBordered target:self action:@selector(sayHello:)];

Another way is to set the target and action after you created it

[buttonHello setTarget:self];
[buttonHello setAction:@selector(sayHello:)];

Target is the instance of the object that will get called. In the case of self, the method will be on this instance of the object.

Action is the method that will get called. Typically, you decorate it with IBAction to hint to the designer that it's an action. It compiles to void.

- (IBAction)sayHello:(id)sender
{
    // code here
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...