UILabel的接收点击消息

需求:PM希望统计下某一处的是否有用户点击,但是之前该处该处是一个静态Text View,所以是通过UILabel来实现的。那么如何使其能够接收点击的消息呢?

最开始设想如果能够想UIButton那么增加一个响应事件,就会比较的方便了。(确实尝试了一把在lable上增加一个button,然后点击button可以相当于点击了lable了的,但是改方法真的是比较挫,不是解决问题的根本)

然后查看UILable的说明:

The UILabel class implements a read-only text view. You can use this class to draw one or multiple lines of static text, such as those you might use to identify other parts of your user interface. 

这个基本说明UILabel是一个只读的textview。

然后往下看,下面讲述到:

New label objects are configured to disregard user events by default. If you want to handle events in a custom subclass ofUILabel, you must explicitly change the value of the userInteractionEnabled property to YES after initializing the object. or information about basic view behaviors, see View Programming Guide for iOS.

这里说讲述到label一般是不响应用户的消息的。然后了解了下IOS的类图,其继承关系为:NSObject-UIResponder-UIView-UILabel。

然后继续看View Programming Guide for iOS.,再看文档中“About Window and Views”,关于window和views是一个常长讨论的问题了的。在该文档的“View Manager Your Application’s Visual Content”中有这么样的介绍:A view responds to touch events in its rectangular area either by using gesture recognizers or by handling touch events directly. 

这句话很关键啊,可以采用手势来解决这个问题:

具体的手势可以查看UITapGestureRecognizer当中的介绍,我们这里增加一个“单点”的事件

    UITapGestureRecognizer* singleRecognizer = [[UITapGestureRecognizer alloc]

                                                initWithTarget:self action:@selector(AddressLabelSingleTap:)];

    singleRecognizer.numberOfTapsRequired = 1; //单击

    singleRecognizer.delegate = self;

    [AddressLabelSingleTap  addGestureRecognizer:singleRecognizer];

基本的逻辑是定义一个手势的对象,然后设置其是单击,设置代理(别忘记增加UIGestureRecognizerDelegate的协议)

然后通过addGestureRecognizer的方法将两者关联起来。

完成以上之后,发现还是无法响应点击的消息。哦~ 然后想到上面看到的需要设置一个属性为YES

然后增加AddressLabel.userInteractionEnabled = YES;

就能够成功的接收到点击的消息了的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值