简体   繁体   中英

How can I programmatically link an UIView or UIImageView with an event like “touch up inside”?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM