如何在目标c中的collectionsviewcell中处理Custombutton CheckedAnduncheck功能并进行多选

时间:2016-05-10 11:32:07

标签: ios objective-c uicollectionviewcell

我想要collectionview单元格,其中我放置了用于向group.multiselection添加成员的自定义按钮复选框。但是当我选择特定复选框时,还选择了另一个不可见的复选框,它位于相同的索引路径从下面的lastvisible单元格是我的代码 `

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
 CGCell *cell = [_CGCol dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
[cell.btn addTarget:self action:@selector(CheckUncheckFunctionality:) forControlEvents:UIControlEventTouchUpInside];
    cell.btn.tag = indexPath.row;
return cell;
}
-(void)CheckUncheckFunctionality:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    if (btn.selected) {
      [btn setImage:[UIImage imageNamed:@"unchacked.png"] forState:UIControlStateNormal];
    }
    else{
        [btn setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
    }
}

`

2 个答案:

答案 0 :(得分:1)

该单元格可能会被重用。并且由于在cellForItemAtIndexPath方法返回单元格时它们没有更新单元格,因此它们处于上次更新状态。解决方案: -

我认为你正在使用模型来获取细胞信息

  1. 在模型中添加一个布尔标志,用于存储是否选中该项目。最初是假的
  2. 当您返回单元格时,将检查单元格的标志值的模型。并相应地更新按钮状态。

答案 1 :(得分:1)

声明全局数组并初始化

NSMutableArray * ArrCheckIndexs=[[NSMutableArray alloc] init];
for (int i=0; i<no.ofcell; i++)
{
    [ArrCheckIndexs addObject:@"0"];
} 

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
 CGCell *cell = [_CGCol dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
 [cell.btn addTarget:self action:@selector(CheckUncheckFunctionality:) forControlEvents:UIControlEventTouchUpInside];
cell.btn.tag = indexPath.row;
return cell;
} 


-(void)CheckUncheckFunctionality:(id)sender
  {
   UIButton *btn = (UIButton *)sender;
   if ([[ArrCheckIndexs objectAtIndex:btn.tag] isEqualToString:@"1"])
    {
      [btn setImage:[UIImage imageNamed:@"unchacked.png"] forState:UIControlStateNormal];
       [ArrCheckIndexs replaceObjectAtIndex:btn.tag withObject:@"0"];
    }
  else
  {
       [btn setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
       [ArrCheckIndexs replaceObjectAtIndex:btn.tag withObject:@"1"];
  }
 }