自定义UILabel,接受触摸事件

本文介绍了iOS应用中UILabel如何处理并传递触控事件。通过自定义UILabel子类myLabel,并重写其touchesBegan方法,实现了当用户点击label时触发特定响应。此外,还探讨了当label的userInteractionEnabled属性为NO时,触控事件如何被父视图捕获。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 #import <UIKit/UIKit.h>
2 
3 @interface myLabel : UILabel
4 
5 @end

 

 1 #import "myLabel.h"
 2 
 3 @implementation myLabel
 4 
 5 - (id)initWithFrame:(CGRect)frame
 6 {
 7     self = [super initWithFrame:frame];
 8     if (self) {
 9         // Initialization code
10     }
11     return self;
12 }
13 
14 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
15     NSLog(@"myLabel touch");
16 }
17 
18 @end

 

 1 #import "ViewController.h"
 2 
 3 @implementation ViewController
 4 
 5 - (void)viewDidLoad
 6 {
 7     [super viewDidLoad];
 8     [self.view setBackgroundColor:[UIColor greenColor]];
 9     
10     myLabel *label = [[myLabel alloc] init];
11     label.frame = CGRectMake(60, 100, 200, 50);
12     label.text = @"Hello world";
13     label.backgroundColor = [UIColor blueColor];
14     
15     label.userInteractionEnabled = YES;
16     
17     [self.view addSubview:label];
18 }

 19  - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

  20    NSLog(@"viewController touch");

  21 }

 

如果label.userInteractionEnabled = NO; (默认值),当用户点击label时将显示“viewController touch”。

 

如果在myLabe中加入:

1 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
2     NSLog(@"myLabel touch");
3     [self.nextResponder touchesBegan:touches withEvent:event];  // 接受到事件后继续向上传递事件
4 }

 

转载于:https://www.cnblogs.com/sell/archive/2013/02/19/2917064.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值