【问题标题】:Accessing CollectionViewCell访问 CollectionViewCell
【发布时间】:2017-06-08 05:14:24
【问题描述】:

我在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]];
 }

【问题讨论】:

  • [NSIndexPath indexPathForRow: button.tag inSection:0],获取完整代码[self.productCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow: button.tag inSection:0]];
  • @anbu-karthik :感谢您编辑答案
  • @Anbu.Karthik,非常感谢它的工作。我没有添加该部分,我想如果我不设置它,那么它将分配为零作为默认值。请把你的代码作为答案,我会接受它。
  • @SandeepBhandari - 没关系,我的兄弟,
  • @hotspring - 检查 sandeepbhandari 的答案也一样,接受那个答案

标签: ios objective-c uicollectionview


【解决方案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]];

希望对你有帮助。

【讨论】:

    【解决方案2】:

    如果你想不带标签,那么

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      相关资源
      最近更新 更多