访问CollectionViewCell

时间:2017-06-08 05:14:25

标签: ios objective-c uicollectionview

我在collectionviewcell上添加了一个按钮,一旦用户点击该按钮,它就会调用以下方法,但uviCollectionViewCell返回nil。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(collectionView == productCollectionView)
    {
        __weak ProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

        cell.addBtnOutlet.tag = indexPath.row;
        [cell.addBtnOutlet addTarget:self
                        action:@selector(collectionViewCellAddButtonPressed:)
              forControlEvents:UIControlEventTouchUpInside];
    }
  return cell;
}

- (IBAction)collectionViewCellAddButtonPressed:(UIButton *)button{
     NSLog(@"Add Button Clicked" );
     // the following is nil
     UICollectionViewCell *uviCollectionCell =  [self.productCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathWithIndex:0]];
 }

2 个答案:

答案 0 :(得分:1)

你需要的只是,

如果您需要索引路径等于按钮标记的单元格,那么Karthik说,

UICollectionViewCell *uviCollectionCell = [self.collectionView.dataSource collectionView:self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:button.tag inSection:0]];

如果您需要始终在索引路径0,0处使用单元格,请使用

UICollectionViewCell *uviCollectionCell = [self.collectionView.dataSource collectionView:self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

希望它有所帮助。

答案 1 :(得分:1)

如果你想没有标签,那么

- (IBAction)collectionViewCellAddButtonPressed:(UIButton *)button{
    NSLog(@"Add Button Clicked" );
    UICollectionViewCell *uviCollectionCell =  (UICollectionViewCell *)button.superview;

    // if this is return nil then use like below as i am not sure it will retuen contentview for superview
    UICollectionViewCell *uviCollectionCell1 =  (UICollectionViewCell *)button.superview.superview;
 }