uilabel添加点击事件需要用到UITapGestureRecognizer对象,用法非常简单,下面是UITapGestureRecognizer的使用案例。
- (void)viewDidLoad { [super viewDidLoad]; //创建uilabel UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 60, 120, 30)]; label.text = @"点击label按钮"; label.textColor = [UIColor whiteColor]; label.backgroundColor = [UIColor orangeColor]; [self.view addSubview:label]; //label添加点击事件 UITapGestureRecognizer *labelTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickUILabel:)]; //可以label传递给UITapGestureRecognizer对象 [label addGestureRecognizer:labelTap]; label.userInteractionEnabled = YES; } - (void)clickUILabel:(UITapGestureRecognizer *)labelTap{ //获取被点击label的内容 UILabel *label = (UILabel *)labelTap.view; NSLog(@"%@",label.text); }
UITapGestureRecognizer这个操作uilabel的方法很常用,一定要学会哦。