Add a custom selector to a UIBarButtonItem

你离开我真会死。 提交于 2019-11-28 07:38:08

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
}
Luke

There's a variety of different init calls you can use, listed in the Instance Methods section here:

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIBarButtonItem_Class/Reference/Reference.html

- (id)initWithBarButtonSystemItem:(UIBarButtonSystemItem)systemItem target:(id)target action:(SEL)action
- (id)initWithCustomView:(UIView *)customView
- (id)initWithImage:(UIImage *)image style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action
- (id)initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action

Also, you can check out a sample in-use here:

How to set target and action for UIBarButtonItem at runtime

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!