xcode IB 中的点击手势识别器可以用于 UILabel 和/或 UIImageView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8134637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can a Tap Gesture Recognizer in IB be used on a UILabel and/or UIImageView
提问by user278859
I have an xib with a single UIView containing a bunch of images and labels. If I drag a Tap Gesture Recognizer onto the parent view, it works well, but I need to add code to determine the position of the tap so I can respond properly to the label tapped.
我有一个带有单个 UIView 的 xib,其中包含一堆图像和标签。如果我将 Tap Gesture Recognizer 拖到父视图上,它运行良好,但我需要添加代码来确定点击的位置,以便我可以正确响应点击的标签。
I thought it would be a lot easier if I could instead drag Gesture Recognizers to each label and/or image and wire IBActions to each where I respond respond appropriately. Unfortunately I cannot get this to work. I can only get the delegate methods to execute from the parent view.
我认为如果我可以将手势识别器拖到每个标签和/或图像并将 IBActions 连接到我做出适当响应的每个位置,那会容易得多。不幸的是,我无法让它发挥作用。我只能从父视图中获取要执行的委托方法。
What I did was drag a Tap Gesture Recognizer to a label, then wired the view controller as the TGR's delegate, and wired an IBAction method to handle the tap. In addition to using the IBAction method I tried without succes assigning the target and action method in the gestureRecognizerShouldBegin:gestureRecognizer delegate method.
我所做的是将一个 Tap Gesture Recognizer 拖到一个标签上,然后将视图控制器连接为 TGR 的代理,并连接一个 IBAction 方法来处理点击。除了使用 IBAction 方法,我尝试在gestureRecognizerShouldBegin:gestureRecognizer 委托方法中分配目标和动作方法都没有成功。
Shouldn't this work, or am I just wishfully thinking?
这不应该奏效,还是我只是一厢情愿?
Thanks for any help.
谢谢你的帮助。
John
约翰
回答by salo.dm
On UIImages and UILabels, userInteractionEnabled
is set to NO by default. You can use a gesture recognizer with both of them, but first you have to reset this property.
在 UIImages 和 UILabels 上,userInteractionEnabled
默认设置为 NO。您可以对它们使用手势识别器,但首先您必须重置此属性。
In Interface Builder or Storyboard, on the label or the image, check the box for userInteractionEnabled.
在 Interface Builder 或 Storyboard 中,在标签或图像上,选中 userInteractionEnabled 框。
Or, in code, just do as follows (Objective-C):
或者,在代码中,只需执行以下操作(Objective-C):
myLabel.userInteractionEnabled = YES;
myImage.userInteractionEnabled = YES;
(Swift):
(迅速):
myLabel.userInteractionEnabled = true
myImage.userInteractionEnabled = true