爲UILable添加點擊事件,首先必須設置UILabel的userInteractionEnabled = YES,添加的點擊事件纔會有效,否則無效。
首先設置label1和label2兩個屬性,這裏label1的點擊原理是判斷點擊的座標是否在label1的範圍內,如果在範圍內的話就變藍色,否則變紅色,label1的代碼被註釋了,爲了測試label2。
label2是直接給label2添加單擊事件
具體代碼如下:
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap1:)];
// [self.view addGestureRecognizer:tap1];
UITapGestureRecognizer *uiTap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap2:)];
self.label2.userInteractionEnabled = YES;
[self.label2 addGestureRecognizer:uiTap2];
}
- (void)tap1:(UITapGestureRecognizer *)param{
NSLog(@"--------");
CGPoint point = [param locationInView:self.view];
if(CGRectContainsPoint(_label1.frame, point)){//如果單擊的座標在label範圍之內,則變藍色,否則變紅色
_label1.backgroundColor = [UIColor blueColor];
} else {
_label1.backgroundColor = [UIColor redColor];
}
}
- (void)tap2:(UITapGestureRecognizer *)param{
NSLog(@"=========");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end