处理 UILabel 中的触摸事件并将其连接到 IBAction
好的,我在界面生成器中创建了一个 UILabel,它显示一些“点击开始”的默认文本。
当用户点击 UILabel 时,我希望它触发 IBAction 方法: -(IBAction)next;
更新标签上的文本以表达新内容。
如果这允许我简单地将连接从我的方法拖到我的标签,然后选择内部的修饰(就像使用按钮一样),那将非常方便。但可惜的是,没有雪茄。
所以无论如何,我想我的问题是,我是否必须子类化 UILabel 才能使其正常工作?或者有什么方法可以将按钮拖动到标签上,但使其 0% 不透明。或者我缺少一个更简单的解决方案?
Ok, so I have a UILabel
created in interface builder that displays some some default text of "tap to begin".
When the user taps the UILabel
I want it to trigger an IBAction method:-(IBAction)next;
which updates the text on the label to say something new.
It would be really convenient if this allowed me to simply drag a connection from my method to my label and then select touch up inside, as with a button. but alas, no cigar.
so anyways, I guess my question is, am I going to have to subclass UILabel
to get this to work? Or is there some way I can drag a button over the label, but make it 0% opaque. Or is there a simpler solution I'm missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看看吧:
诀窍是启用用户交互。
Check it out:
The trick is to enable user interaction.
UILabel继承自UIView,而UIView继承自UIResponder。所有 UIresponder 对象都可以处理触摸事件。因此,在了解您的视图(包含 UIlabel)的类文件中实现:
在界面生成器中设置 UILabel 的标记值。当touchesBegan方法中发生触摸时,检查标签所属视图的标签值:
通过使用IBOutlet前缀声明UILabel实例变量,将类文件中的代码与界面生成器中的UILabel对象连接起来:
然后在界面中您可以将它们连接起来。
UILabel inherits from UIView which inherits from UIResponder. All UIresponder objects can handle touch events. So in your class file which knows about your view (which contains the UIlabel) implement:
In interface builder set the UILabel's tag value. when touches occur in your touchesBegan method, check the tag value of the view to which the tag belongs:
You connect your code in your class file with the UILabel object in interface builder by declaring your UILabel instance variable with the IBOutlet prefix:
Then in interface builder you can connect them up.
您可以使用 UIButton,使其透明,即没有图像的自定义类型,并在其上添加 UILabel(居中)。然后连接正常的按钮事件。
You can use a UIButton, make it transparent, i.e. custom type without an image, and add a UILabel on it (centered). Then wire up the normal button events.
Swift 3
您有一个 IBOutlet
,您可以在其中启用用户交互并添加手势识别器
最后,处理点击
Swift 3
You have an IBOutlet
In which you enable user interaction and add a gesture recognizer
And finally, handle the tap