UICollectionView cellForIndexPath返回错误的值

时间:2016-06-16 11:44:41

标签: ios objective-c uicollectionview row nsindexpath

我在UIButton中使用UICollectionVIew,点按该按钮我想知道cell的索引,所以我使用以下代码

  setFrpPriceButton.tag = indexPath.item;

但我获得的价值不正确。 以下代码我为UICollectionView

撰写
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return frpTitleArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{

    setFrpPriceButton = [UIButton new];
    setFrpPriceButton.backgroundColor = UIColorFromRGB(0x2196f3);
    [setFrpPriceButton setTitle:@"SET PRICE" forState:UIControlStateNormal];
    [setFrpPriceButton addTarget:self action:@selector(setFrpPriceClick) forControlEvents:UIControlEventTouchUpInside];
    setFrpPriceButton.tag = selectedCellIndex;

    [frpCollectionViewCell addSubview:setFrpPriceButton];
//    [frpButtonLabel bringSubviewToFront:setFrpPriceButton];
    setFrpPriceButton.titleLabel.font = [UIFont boldSystemFontOfSize:10];
    setFrpPriceButton.clipsToBounds = YES;

    [setFrpPriceButton mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.top.equalTo(frpButtonLabel);
         make.width.equalTo(frpCollectionViewCell).dividedBy(3);
         make.right.equalTo(frpCollectionViewCell);
         make.height.equalTo(frpTitleLabel);
     }];

    return frpCollectionViewCell;
}

- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)displaySpecialityCollectionView
{
    return 1;
}

- (CGSize)collectionView:(UICollectionView *)displaySpecialityCollectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(self.view.frame.size.width, self.view.frame.size.height/2);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)displaySpecialityCollectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0,0,0,0);
}

- (void)collectionView:(UICollectionView *)displaySpecialityCollectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
}

1 个答案:

答案 0 :(得分:-1)

你应该写自定义单元格。并且该按钮应位于自定义单元格中。并为cellForItemAtIndexPath添加设置按钮的标记。

现在问题是在重复使用的单元格中重复添加按钮,因此您将无法获得正确的标记。

用于创建自定义单元格。 Documents > Dot Notation > Embedded Documents