UITapGestureRecognizer 不能添加到 UIView 中?

Posted

技术标签:

【中文标题】UITapGestureRecognizer 不能添加到 UIView 中?【英文标题】:UITapGestureRecognizer doesn't work added to an UIView? 【发布时间】:2011-03-30 10:39:02 【问题描述】:

我正在尝试为简单的 UIView 制作手势识别器:

UIView *theView = [[UIView alloc] initWithFrame:rect];
[theView setUserInteractionEnabled:YES];

UITapGestureRecognizer *tap = [[[UITapGestureRecognizer alloc] initWithTarget:self 
                                                                       action:@selector(handleTap)] autorelease];
[theView addGestureRecognizer:tap];

如果我调试视图的属性gestureRecognizers,它会显示手势识别器对象。但是当我在视图中点击时它不起作用。

使用 UIImageView 的相同代码完美运行,任何想法为什么在 UIView 中不起作用?

更新:

一个示例类。

@implementation ExampleClass

- (UIView *)getViewInRect:(CGRect)rect

    UIView *theView = [[UIView alloc] initWithRect:rect];
    [theView setUserInteractionEnabled:YES];

    UITapGestureRecognizer *tap = [[[UITapGestureRecognizer alloc] 
                                    initWithTarget:self 
                                    action:@selector(handleTap)] 
                                   autorelease];
    [aText addGestureRecognizer:tap];

    return theView;


- (UIImageView *)getImageViewInRect:(CGRect)rect

    UIImageView *theView = [[UIImageView alloc] initWithRect:rect];
    [theView setUserInteractionEnabled:YES];

    UITapGestureRecognizer *tap = [[[UITapGestureRecognizer alloc] 
                                        initWithTarget:self 
                                                action:@selector(handleTap)] 
                                   autorelease];
    [theView addGestureRecognizer:tap];

    return [theView autorelease];    


- (void)handleTap

    NSLog(@"Tap Handled!!", nil);


@end

更新 2:

将 UITapGestureRecognizer 添加到 theView 的所有子视图并不能解决问题...

修复它!!!

好的!!问题是 theView 的 CGRect,它的宽度设置为 0.0!!!

【问题讨论】:

你的 handleTap 函数是什么样的?您是否在 theView 的 Superview 中使用了手势识别器,可以捕捉到手势? handleTap 是上述代码所在类的方法。从这个独家新闻中,我可以毫无问题地使用 [self handleTap] 调用它。 你是说如果你在上面的代码 sn-p 中将UIView 替换为UIImageview 就可以了吗? 那……不应该。显示更多代码:) @freespace 查看更新,是来自项目的 C&P 代码(我无法显示更多)。这似乎是一个笑话! :-S 【参考方案1】:

你试过了吗?

[view setUserInteractionEnabled:YES];

【讨论】:

【参考方案2】:

在 .h 文件中将视图声明为 ivar。合成然后这样调用:

[self.theview setMultipleTouchEnabled:YES];

不要忘记在 viewDidLoad 方法中分配和初始化该视图。

就是这样。

【讨论】:

以上是关于UITapGestureRecognizer 不能添加到 UIView 中?的主要内容,如果未能解决你的问题,请参考以下文章

UITapGestureRecognizer 不能(总是)为不同于 UIViewController 的目标工作

我可以将 UITapGestureRecognizer 添加到我的控制器 self.view,但不能添加到任何自定义视图。为啥?

为什么UITapGestureRecognizer不能在keyWindow(全屏)的子视图中工作?

获取 UITapGestureRecognizer 目标

有没有办法通过 UITapGestureRecognizer 发送对象?

如何为uiview的不同部分添加多个UITapGestureRecognizer?