【问题标题】:UITapGestureRecognizer doesn't work added to an UIView?UITapGestureRecognizer 不能添加到 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

标签: iphone objective-c tap


【解决方案1】:

你试过了吗?

[view setUserInteractionEnabled:YES];

【讨论】:

    【解决方案2】:

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

    [self.theview setMultipleTouchEnabled:YES];
    

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

    就是这样。

    【讨论】:

      猜你喜欢
      • 2018-10-07
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多