我正在通过代码制作动态 UIViews
并尝试在它们上面添加 UITapGestureRecogniser
。但出于某种原因,他们没有回应。这是代码:
-(void)createRandomBlock{
UIView * block = [[UIView alloc] initWithFrame:CGRectMake([self getRandomPosition], 0-_heightOfBlock, _widthOfBlock, _heightOfBlock)];
block.backgroundColor = [self randomColor];
block.userInteractionEnabled=YES;
UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(blockTapped:)];
tapGesture.delegate = self;
tapGesture.numberOfTouchesRequired = 1;
tapGesture.numberOfTapsRequired=1;
[block addGestureRecognizer:tapGesture];
[self.view addSubview:block];
[UIView animateWithDuration:_durationOfAnimation delay:0.0 options:options animations:^{
[block setFrame:CGRectMake(block.frame.origin.x, ScreenHeight, block.bounds.size.width, block.bounds.size.height)];
} completion:^(BOOL finished) {
[block removeFromSuperview];
}];
}
-(void)blockTapped:(UITapGestureRecognizer*)gesture{
NSLog(@"I am being called?");
UIView * block = (UIView*)[gesture view];
[block removeFromSuperview];
}
有人可以帮忙吗?
谢谢
最佳答案
我尝试使用相同的代码,它对我有用。 唯一的变化是,我没有为 tapGesture 设置委托(delegate)。
-(void)createRandomBlock{
UIView * block = [[UIView alloc] initWithFrame:randomPosition];
block.backgroundColor = [self randomColor];
block.userInteractionEnabled=YES;
UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(blockTapped:)];
tapGesture.numberOfTapsRequired=1;
[block addGestureRecognizer:tapGesture];
[self.view addSubview:block];
}
-(void)blockTapped:(UITapGestureRecognizer*)gesture{
NSLog(@"I am being called?");
UIView * block = (UIView*)[gesture view];
[block removeFromSuperview];
}
我猜是因为添加了委托(delegate),它会覆盖您指定的选择器并改为调用委托(delegate)方法。
关于ios - ONTapGesture 不适用于动态创建的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36693387/