我创建了一个自定义的UIView并在其中添加了一个UITapGestureRecognizer,如下所示:
@interface CustomizedView : UIView
@property(nonatomic,strong) UILabel* label;
@end
@implementation CustomizedView
-(void) targetActionForThisView:(id)sender{
NSLog(@"Clicked!");
}
-(void) commonInit{
_label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,100)];
_label.text = @"test string 1234";
UITapGestureRecognizer* g = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(targetActionForThisView:)];
g.enabled = YES;
[self setExclusiveTouch:YES];
[self setUserInteractionEnabled:YES];
[self setMultipleTouchEnabled:YES];
[_label addGestureRecognizer:g];
[self addSubview:_label];
}
-(instancetype)init{
self = [super init];
[self commonInit];
return self;
}
-(instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
[self commonInit];
return self;
}
@end
然后我将它添加到视图控制器中:
-(void)viewDidLoad {
[super viewDidLoad];
CustomizedView* aView = [[CustomizedView alloc] initWithFrame:CGRectMake(0,0,300,300)];
[self.view addSubview:aView];
}
但这种姿态不会起作用。 我知道通常将目标设置为视图的控制器。 但为什么这不起作用?我该如何解决?
答案 0 :(得分:0)
将您的代码更改为此
-(void)actionViewTap:(id)sender{
NSLog(@"Clicked!");
}
-(void) commonInit{
_label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,100)];
_label.text = @"test string 1234";
_label.userInteractionEnabled = true;//Enable userInteractionEnabled
UITapGestureRecognizer* g = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(actionViewTap:)];//Here should be actionViewTap:
g.enabled = YES;
[self setExclusiveTouch:YES];
[self setUserInteractionEnabled:YES];
[self setMultipleTouchEnabled:YES];
[_label addGestureRecognizer:g];
[self addSubview:_label];
}
-(instancetype)init{
self = [super init];
[self commonInit];
return self;
}
-(instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
[self commonInit];
return self;
}
答案 1 :(得分:0)
您需要在所需的视图上添加UITapGestureRecognizer对象,这是标签对象。
[_l addGestureRecognizer:g];
应该成为:
[_label addGestureRecognizer:g];