2011-03-30 47 views
5

我triyng做了一個簡單的UIView手勢識別:UITapGestureRecognizer無法添加到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的所有子視圖不解決問題......

解決它!

OK !!問題是該CGView的CGRect,它的寬度設置爲0.0!

+0

你的handleTap函數看起來像什麼? 您是否在theView的Superview中使用了gestureRecognizer,可以捕捉到手勢? – Seega 2011-03-30 10:44:25

+0

handleTap是上述代碼所在的同一類的一種方法。從這個獨家新聞我可以沒有問題[自我處理]。 – 2011-03-30 10:56:33

+1

你是說如果你在上面的代碼片段中用'UIImageview'代替'UIView',它的工作原理是什麼? – freespace 2011-03-30 11:20:03

回答

2

在.h文件中聲明視圖爲ivar。合成,然後像這樣調用它:

[self.theview setMultipleTouchEnabled:YES]; 

不要忘記在viewDidLoad方法中alloc和init的view。

就是這樣。

+1

不解決問題,抱歉:-( – 2011-03-30 11:59:11

19

你試過這個嗎?

[view setUserInteractionEnabled:YES];