2015-04-16 45 views
0

我將MainViewController和LongPressGestureRecognizer添加到MainViewController的視圖中。LongPressGestureRecognizer從視圖後面識別

當我通過添加下面的MainViewController的子視圖控制器作爲longpress手勢操作來調用我的CategoryViewController時。

- (IBAction)longPressClicked:(id)sender { 
    _categoryVC = [[CategoryViewController alloc] initWithNibName:@"CategoryViewController" bundle:nil]; 
    _categoryVC.view.frame = self.view.frame; 
    [self addChildViewController:_categoryVC]; 
    [_categoryVC didMoveToParentViewController:self]; 

} 

我攻長按第一次篩選它加載CategoryViewController兒童控制器和推頂部這是很好的,但我又在做同樣的事情,longPressClicked方法再次調用。

我不知道爲什麼它會這樣做,因爲視圖頂部的CategoryViewController和它具有UserInteractionEnabled。

回答

1

您的操作被多次調用。每次當

  • 手勢被認可(觸落的具體時間)
  • 手勢已經結束(擡起)
  • 手勢時檢測到變化(手指移動)

並且每次添加視圖。

所以,當你觸摸下來,你添加一個視圖,當你擡起你再次添加一個視圖。除了您的手勢識別器,不會取消觸摸跟蹤,只是因爲您在觸摸位置上方添加了視圖。它仍然處理觸動。爲了防止這種只考慮您的操作的狀態如下

- (IBAction)longPressClicked:(id)sender { 
    UILongPressGestureRecognizer *gesture = (UILongPressGestureRecognizer *)sender; 

    if (gesture.state == UIGestureRecognizerStateBegan) { 
     // add your view 
    } 
} 

另一種選擇是,讓您的視圖的弱引用,並檢查您的看法是零。如果是這樣,創建一個新的視圖,並將其添加到您的視圖控制器的子視圖。

@interface ViewController() 
@property (weak, nonatomic) UIView *myView; 
@end 

- (void)longPressClicked:(id)sender { 
    if (!self.myView) { 
     // create view 
     self.myView = [[UIView alloc] init....]; 
    } 
}