带有自定义视图的右侧导航栏按钮不会触发操作

时间:2011-03-02 02:12:23

标签: iphone objective-c

我尝试创建一个右键控制按钮,但触摸该按钮时不会触发该操作。任何想法?

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

1 个答案:

答案 0 :(得分:1)

不幸的是,您无法触发使用自定义视图创建的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 ...