前言:有的时候我们需要点击iamge或者label 让某个控件实现点击事件
注意:这里特别提醒一下,大部分控件如果没有响应方法,那么一般是没有开启控件的用户交互,在本文的代码的label的懒加载里有注释,注意看一下,假如是uiimage 也是要开启才可以使用哦!
第一步:遵守协议 <UIGestureRecognizerDelegate>
第二步:创建控件,并且懒加载控件
/** view */
@property(nonatomic,strong)UIView *myView;
/** label */
@property(nonatomic,strong)UILabel *myLabel;
-(UIView *)myView{
if (_myView == nil) {
_myView = [[UIView alloc]init];
_myView.frame = CGRectMake(100, 100, 100, 100);
_myView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:_myView];
}
return _myView;
}
-(UILabel *)myLabel{
if (_myLabel == nil) {
_myLabel = [[UILabel alloc]init];
_myLabel.frame = CGRectMake(100, 200, 120, 30);
_myLabel.text = @"添加点击手势";
_myLabel.userInteractionEnabled = YES;//开启用户交互
[self.view addSubview:_myLabel];
}
return _myLabel;}
第三步:在当前控制器创建对象,设置方法,设置代理等等
//这个可以加到任何控件上,比如你只想响应WebView,我正好填满整个屏幕
UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[self.myView addGestureRecognizer:singleTap];
singleTap.delegate = self;
singleTap.cancelsTouchesInView = NO;
//这个可以加到任何控件上,比如你只想响应WebView,我正好填满整个屏幕
UITapGestureRecognizer* singleTapLabel = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapLabel:)];
[self.myLabel addGestureRecognizer:singleTapLabel];
singleTapLabel.delegate = self;
singleTapLabel.cancelsTouchesInView = NO;
第四步:实现代理方法和设置的响应方法
/** 代理方法 */
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
/** view的点击响应方法 */
-(void)handleSingleTap:(UITapGestureRecognizer *)sender{
CGPoint point = [sender locationInView:self.view];
NSLog(@"view pointx:%f,y:%f",point.x,point.y);
}
/** Lable的点击响应方法 */
-(void)handleSingleTapLabel:(UITapGestureRecognizer *)sender{
CGPoint point = [sender locationInView:self.view];
NSLog(@"label pointx:%f,y:%f",point.x,point.y);
}
/** 懒加载 */
-(UIView *)myView{
if (_myView == nil) {
_myView = [[UIView alloc]init];
_myView.frame = CGRectMake(100, 100, 100, 100);
_myView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:_myView];
}
return _myView;
}
-(UILabel *)myLabel{
if (_myLabel == nil) {
_myLabel = [[UILabel alloc]init];
_myLabel.frame = CGRectMake(100, 200, 120, 30);
_myLabel.text = @"添加点击手势";
_myLabel.userInteractionEnabled = YES;//开启用户交互
[self.view addSubview:_myLabel];
}
return _myLabel;
}
网友评论