具有自定义视图的右导航栏按钮不会触发动作
问题描述:
我试图创建一个正确的栏按钮,但触摸按钮时不会触发该动作。有任何想法吗?具有自定义视图的右导航栏按钮不会触发动作
button = [[UIBarButtonItem alloc] initWithCustomView:[[UIImageView alloc] initWithImage:image]];
button.action = @selector(myaction);
button.target = self;
self.navigationItem.rightBarButtonItem = button;
[button release];
答
不幸的是,您无法触发使用自定义视图创建的UIBarButtonItem
上的操作。如果您的自定义视图实际上是UIControl
或响应触摸事件的其他内容,则此工作的唯一方法。
如果您需要支持3.2之前的版本,处理这个问题的最佳方法是创建一个按钮而不是图像视图,并在该按钮上设置操作。如果你能逃脱支持3.2+,你可以再补充一个UIGestureRecognizer
到您的视图(顺便说一句:在你的代码,你的图像视图漏水,请参阅下面的正确使用):
// 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
现在将工作如预期的那样,不需要在那里隐藏UIButton
那里,你可能不想...
澄清:如果你碰巧使用UIButton(UIControl的后代)为你的UIBarButtonItem的customView,那么你可以添加一个动作通过添加一个动作到你的UIButton使用这个方法:'[theButton addTarget:self action:@selector(theAction :) forControlEvents:UIControlEventTouchUpInside];' – kevinlawler 2011-10-01 20:30:50