开发者

Right nav bar button with custom view doesn't trigger action

I tried to create a right bar button, but 开发者_Python百科the action doesn't get triggered when the button is touched. any ideas?

button = [[UIBarButtonItem alloc] initWithCustomView:[[UIImageView alloc] initWithImage:image]];
button.action = @selector(myaction);
button.target = self;
self.navigationItem.rightBarButtonItem = button;
[button release];


Unfortunately, you can't trigger actions on UIBarButtonItems that are created with custom views. The only way for this to work is if your custom view is actually a UIControl or something else that responds to touch events.

If you need to support pre-3.2, the best way to deal with this is to create a button instead of an image view, and set the action on the button. If you can get away with supporting 3.2+, you can just add a UIGestureRecognizer to your view (BTW: in your code, your image view is leaking, see below for proper use):

// This works for iOS 3.2+
UIImageView imageView = [[UIImageView alloc] initWithImage:image];

// Add the gesture recognizer for the target/action directly to the image view
// Note that the action should take a single argument, which is a reference to
// the gesture recognizer. To be compatible with actions, you can just declare
// this as (id)sender, especially if you don't use it. So the prototype for your
// action method should be: -(void)myAction:(id)sender or -(void)myAction:(UIGestureRecognizer*)gestureRecognizer
UITapGestureRecognizer tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myAction:)];
[imageView setUserInteractionEnabled:YES];
[imageView addGestureRecognizer:tapRecognizer];
[tapRecognizer release];

// Proceed with configuring the bar button item
UIBarButtonItem button = [[UIBarButtonItem alloc] initWithCustomView:imageView];
[[self navigationItem] setRightBarButtonItem:button];
[button release];
[imageView release]; // you were leaking this

Now it will work as expected without having to fob a UIButton in there that you might not want...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜