gpt4 book ai didi

ios - ONTapGesture 不适用于动态创建的 View

转载 作者:可可西里 更新时间:2023-11-01 05:40:23 26 4
gpt4 key购买 nike

我正在通过代码制作动态 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com