views:

3206

answers:

4

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...

+4  A: 

You can do it with

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents

It's declared in UIControl, see the topic in the documentation called "The Target-Action Mechanism"

pgb
For some reason that doesn't work on an UIImageView... see my update above
Thanks
Could it be that you don't have userInteractionEnabled set to YES? By default, UIImageView has it on NO.
pgb
+2  A: 

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
For some reason that doesn't work on an UIImageView... see my update above
Thanks
+1  A: 

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

Suicidal