Making UILabel touchable

天涯浪子 提交于 2019-12-29 04:36:32

问题


I have a UILabel and I would like to make it react to a touch. I tried putting a button on top of the label, thanks to this I could interact with the button. However, the button cannot be fully transparent, right? I could set an alpha of the button to 0,02, but it is still visible on by background. How to solve this? Maybe I could set the properties in some other way to make them fully invisible? Or is there some other solution?


回答1:


First, why not just use a button and set the button title to the label's contents?

If you can't/don't want to do that, you can also set userInteractionEnabled = YES on the label and then add a gesture recognizer to the label.




回答2:


In Swift:

label.userInteractionEnabled = true
let gestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("labelPressed"))
label.addGestureRecognizer(gestureRecognizer)

Get your click in Action :

func labelPressed(){
    print("Label pressed")
    //Your awesome code.
}



回答3:


I usually do this:

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushAction)];
[myLabel addGestureRecognizer:tap];

I don't know if it works with labels, but then i just make a transparent UIView with the same rect and put it on top.


Okay, i checked, it only works in UIView, but then, do this:

UIView *tapView = [[UIView alloc] initWithFrame:myButton.frame];

And put "tapView" in the addGestureRecognizer-method.



来源:https://stackoverflow.com/questions/5206193/making-uilabel-touchable

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