2012-05-25 140 views
2

我刚刚发现一个UIButton对象有一个方法addTarget来处理UI事件,但是一个UIImageView对象没有这样的方法,所以我们不能在代码中完成它,并且不能使用Interface来添加这样的Action也可以为UIImageView对象创建。可以使用手势识别器,但有没有简单的方法将addTarget添加到UIImageView,以便我们的代码不是部分由手势识别器处理,部分由addTarget方法处理?在iOS上,有没有办法将方法addTarget添加到UIImageView?

+2

为什么不只是使用带背景图像的按钮? – wattson12

+0

同意@ wattson12:任何其他解决方案都只是过分复杂的事情。如果点击需要发生,请将其设置为UIButton,并将UIImageView中的图像设置为所有控件状态的按钮图像。 – WendiKidd

+0

这样按钮看起来就像一个图像,除了它是可以点击的?我认为可能会有副作用,例如在触摸时颠倒图像的颜色,但实际上可能需要根据情况进行设置 –

回答

6

它不应该有太大的麻烦,添加一个手势识别调用同一个选择,你的按钮调用:

UIButton *button = [[UIButton alloc] init]; 
[button addTarget:self action:@selector(tapped:) forControlEvents:UIControlEventTouchUpInside]; 

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]; 
[[self view] addGestureRecognizer:tapRecognizer]; 


- (void)tapped:(id)sender {} 
+0

aha,我最初的担心是我不希望某些UI由'addTarget'处理,有些UI由手势识别器处理。 。 –

0

因为UIImageView的是不是一个子类UIControl(这是UIButton的的超),所以我的解决方案是伪造具有轻击手势的UIControl的行为,并为自定义UIImageView创建addTarget:action方法,使其看起来像其他UIControl类。

我创建了一个子类的UIImageView称为SWImageView,在标题:

- (void)addTarget:(id)target action:(SEL)action; 
在主文件

- (void)addTarget:(id)target action:(SEL)action 
{ 
    if (tapGestureRecognizer!=nil) { 
     [self removeGestureRecognizer:tapGestureRecognizer]; 
    } 
    tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:target action:action]; 
    [self addGestureRecognizer:tapGestureRecognizer]; 
}  

不要忘了让用户交互:

self.userInteractionEnabled = YES; 
相关问题