简体   繁体   English

UITapGestureRecognizer无法添加到UIView?

[英]UITapGestureRecognizer doesn't work added to an UIView?

I'm triyng to make a gesture recognizer for a simple UIView: 我想为一个简单的UIView做一个手势识别器:

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

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

If I debug the property gestureRecognizers of the view it shows the gesture recognizer object. 如果我调试视图的属性gestureRecognizers,它会显示手势识别器对象。 But when I tap inside the view it doesn't work. 但是当我点击视图内部时,它不起作用。

The same code using an UIImageView works perfect, any ideas why doesn't work in UIView? 使用UIImageView的相同代码完美无缺,任何想法为什么在UIView中不起作用?

UPDATED: 更新:

An example class. 一个示例类。

@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

UPDATED 2: 更新2:

Adding UITapGestureRecognizer to all subviews of theView don't fix the problem... 将UITapGestureRecognizer添加到View的所有子视图不能解决问题...

FIX IT!!! 修理它!!!

OK!! 好!! The problem was the CGRect for theView, it had the width set to 0.0!!! 问题是CGRect for theView,它的宽度设置为0.0!

你试过这个吗?

[view setUserInteractionEnabled:YES];

Declare theview as ivar in .h file. 在.h文件中将视图声明为ivar。 Synthesize and then call it like this: 合成然后像这样调用它:

[self.theview setMultipleTouchEnabled:YES];

Don't forget to alloc and init that theview in viewDidLoad method. 不要忘记在viewDidLoad方法中分配和初始化该视图。

That's it. 而已。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM