自定义UILabel,接受触摸事件

本文介绍了如何在iOS开发中自定义UILabel,并实现接受触摸事件的功能。通过代码示例展示了初始化、设置帧、文本和背景颜色,以及如何通过UIResponder系统处理触摸事件。

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

自定义UILabel,接受触摸事件

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 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值