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

喜夏-厌秋 提交于 2019-12-01 07:24:31

问题


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


回答1:


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




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/910334/how-can-i-programmatically-link-an-uiview-or-uiimageview-with-an-event-like-tou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!