On iOS, is there a way to add the addTarget method to a UIImageView?

I just found that the object UIButtonhas a method addTargetfor handling user interface events, but the object UIImageViewdoes not have such a method, so we cannot do this in the code and can't add such an action using the Interface Builder for the object UIImageView. You can use the gesture recognizer, but is there a simple way to add addTargetin UIImageViewso that our code is not partially processed by the gesture recognizer and partially processed by the method addTarget?

+3
source share
2 answers

No need to add a lot of gesture recognizer, which calls the same selector as your button:

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 {}
+7

UIImageView UIControl ( UIButton), UIControl, addTarget: action UIImageView, 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;
0

All Articles