簡體   English   中英

iOS為什么不能從UITapGestureRecognizer調用方法collectionView:didSelectItemAtIndexPath :?

[英]iOS Why can't the method collectionView:didSelectItemAtIndexPath: be called from UITapGestureRecognizer?

我已經在UICollectionView內為UIScrollView設置了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
}

您編寫的代碼,

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

選擇器通常只是具有一個輸入參數(即UITapGestureRecogniser對象)的UITapGestureRecogniser

應該是這樣的

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

}

但是您使用的選擇器使用不當,因為它需要兩個不能隨手勢識別器一起提供的輸入。

將上面的代碼更改為下面的代碼,

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];

}

手勢識別器的動作必須符合以下簽名之一:

- (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

我們必須從適當的引用對象中調用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];

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM