3

Interface Builder will only allow me to hook up such events for an button. But like in HTML, I just want to haven an blank UIImageView where - as soon as the user taps it - a method is invoked. I hope there is some cool programmatically way of doing that, which I don't know about.

UPDATE:

In my View Controller that creates the UIImageView I tried to do this:

SEL actionSelector = @selector(doSomethingWhenImageIsTouched:);
[self.myUIImageView addTarget:nil action:actionSelector forControlEvents:UIControlEventTouchUpInside];

The compiler gives me a warning, that UIImageView may not respond to addTarget:... what do I have to do so that it works with an UIImageView. I see in the docs that UIImageView does not inherit from UIControl, but addTarget: is part of UIControl.

UPDATE:

I ended up creating an UIButton after creating the UIImageView. Then I set the frame of that button to the frame of the UIImageView, and alpha to 0.1f. For some reason, it will not work if alpha is 0.0f. And then, I did that cool addTarget: thing...

Thanks
  • 40,109
  • 71
  • 208
  • 322
  • Would be more appropriate to call the touchesBegan or touchesEnded methods and check the touched view there. – lostInTransit May 26 '09 at 12:28
  • @lostInTransit - That's what I did recently. Works like a charm. Perhaps you could make it an answer? – Kriem May 26 '09 at 13:15
  • 1
    Regarding the alpha of 0.1, hitTest:withEvent: ignores views that are hidden, have disabled user interaction or have an alpha of less than 0.1 (see hitTest under UIView class reference) – progrmr Mar 16 '10 at 03:23

3 Answers3

4

In SDK version 3.2 (could be earlier i donno), you can add gesture recognizers to a UIView. UIGestureRecogniser is an abstract class that allows you to define a gesture (tap, pinch, swipe, etc) and add it to a UIView and when the gesture recognizer, recognizes the gesture, it fires up an action on a target of your desire.

read all about it in the docs... :D

Alex Zak
  • 1,924
  • 2
  • 18
  • 26
1

It is not possible to use Target-Action Model here because UIImageView is not inherited from UIControl like UIButton it is derived from UIView. So if u want to track the touches on views or image views first u have to custom class and then place the touch began event in to it and perform the operation. Otherwise use UIGestures that may help u lot

vignesh
  • 11
  • 1
0

UIViews don't generally need IBAction outlets to receive touch events. Typically, if a view is under the control of a viewController, you can check for UITouch Events using touchesBegan methods. To set the target and selector for control actions you can also use:

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents
Jordan
  • 21,746
  • 10
  • 51
  • 63