簡體   English   中英

如何在按鈕單擊上獲取和傳遞UICollectionViewCell

[英]How to I get and pass a UICollectionViewCell on a button click

在集合視圖單元格中,我有三個按鈕,而沒有單擊/選擇UICollectionViewCell ,如何獲得被單擊按鈕的索引路徑?

到目前為止,這是我的代碼:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    UIButton * button = (UIButton *)[cell viewWithTag:10];
    UILabel * labelTitle = (UILabel *)[cell viewWithTag:20];
    UIButton * shareBtn = (UIButton *)[cell viewWithTag:30];
    UIButton * editBtn = (UIButton *)[cell viewWithTag:40];
    [shareBtn addTarget:self action:@selector(shareDoc:) forControlEvents:UIControlEventTouchUpInside];
    [editBtn addTarget:self action:@selector(editDoc) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

-(void)shareDoc:(UICollectionViewCell *) senderCell
{
    UICollectionView * collectionView = [self.view viewWithTag:22];
    UICollectionViewCell * cCell = [self.view viewWithTag:11];

    NSIndexPath * indexPath = [collectionView indexPathForCell:cCell];
    NSLog(@"cell: %ld", indexPath.row); //But this just returns 0 every time I clicked on a button.
    NSLog(@"section: %ld", indexPath.section);


}

您可以使用indexPathForItemAtPoint:並使用將事件作為參數的操作方法。 像這樣:

- (IBAction)shareDoc:(id)inSender forEvent:(UIEvent * )inEvent {
    UITouch *theTouch = inEvent.allTouches.anyObject;
    CGPoint thePoint = [theTouch locationInView:self.collectionView];
    IndexPath *theIndexPath = [self.collectionView indexPathForItemAtPoint:thePoint];

    ...
}

您還應該更改按鈕的Target-Action分配:

[shareBtn addTarget:self action:@selector(shareDoc:forEvent:) forControlEvents:UIControlEventTouchUpInside];

由於這些答案 ,如果滾動后索引路徑錯誤,則應添加contentOffset

- (IBAction)shareDoc:(id)inSender forEvent:(UIEvent * )inEvent {
    UITouch *theTouch = inEvent.allTouches.anyObject;
    CGPoint theOffset = self.collectionView.contentOffset
    CGPoint thePoint = [theTouch locationInView:self.collectionView];
    IndexPath *theIndexPath = [self.collectionView indexPathForItemAtPoint:CGPointMake(thePoint.x + theOffset.x, thePoint.y + theOffset.y)];

    ...
}

但這對我來說似乎很奇怪。

您可以嘗試此操作,自定義您的單元格或使用標簽(無論如何)以確保索引路徑,然后使用UIResponder傳遞您的SEL。 例如,

@interface UIResponder (PassAction)

- (void)passAction:(NSString *)actionName otherInfo:(NSDictionary *)otherInfo;

@end

U可以像這樣觸發您的單元格:

[self passAction:NSStringFromClass([cell class]) userInfo:@{@"Tag":@(cell.tag)}];

在controller中,實現如下:

- (void) passAction:(NSString *)eventName otherInfo:(NSDictionary *)userInfo{
    NSLog(@"success");
}

暫無
暫無

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

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