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

标签 ios objective-c uitapgesturerecognizer

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

相关文章:

ios - 自定义 UIBarButtonItem

ios - SceneKit - 绘制 3D 抛物线

swift - UITapGestureRecognizer 崩溃应用程序..?

ios - 如何使 UILabel 可点击?

android - Phonegap/Cordova 相机插件 - 如何获取照片的日期/时间戳?

ios - swift 3 : Cannot automatically unwrap optional before setting it to Label

ios - 需要有关 UIActionSheet 的帮助

ios - 选择器获取indexPath UICollectionView Swift 3.0

ios - Swift 中的零宽度空间?

iphone - 在 iPhone 上使用 CoreData 或 SQLite?