0

我已經爲UICollectionView內的UIScrollView設置了UITapGestureRecognizer。我已經配置它來正確檢測點擊並觸發我寫的一個方法,但是如果我嘗試將選擇器設置爲collectionView:didSelectItemAtIndexPath:當單擊一個單元格時程序崩潰。iOS爲什麼不能從UITapGestureRecognizer調用方法collectionView:didSelectItemAtIndexPath:?

任何想法爲什麼這種情況?

這工作:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]; 

- (void) tapped:(UIGestureRecognizer *)gesture{ 
//some code 
} 

這不起作用:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(collectionView:didSelectItemAtIndexPath:)]; 

- (void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
//some code 
} 

回答

5

你寫的代碼,

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(collectionView:didSelectItemAtIndexPath:)]; 

的選擇通常僅僅是一個singleFunction一個輸入參數這是UITapGestureRecogniser對象。

應該是這樣的,

-(void)clicked:(UIGestureRecogniser *)ges{ 

} 

但你用它不當的選擇,因爲它需要哪些不能用gestureRecogniser.Hence崩潰提供兩個輸入。

更改上面的代碼下面一個,

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clicked:)]; 
-(void)clicked:(UIgestureRecogniser *)ges{ 
    //use gesture to get get the indexPath, using CGPoint (locationInView). 
    NSIndexPath *indexPath = ...; 
    [self collectionView:self.collectionView didSelectItemAtIndexPath:indexPath]; 

} 
1

的手勢識別的行動必須符合以下特徵之一:

- (void)handleGesture; 
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer; 

你需要使用這些動作簽名之一併在該方法 中做任何您需要的操作,包括確定手勢的正確indexPath

請參閱該文檔: https://developer.apple.com/library/ios/documentation/uikit/reference/UIGestureRecognizer_Class/Reference/Reference.html#//apple_ref/occ/instm/UIGestureRecognizer/initWithTarget:action

0

我們必須調用從適當的參考對象didSelectItemAtIndexPath。

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]; 

- (void) tapped:(UIGestureRecognizer *)gesture{ 

     NSIndexPath *indexPath = //create your custom index path here 

     [self.collectionViewObject didSelectItemAtIndexPath:indexPath]; 

} 
相關問題