如何使用多选处理 objective c 中的集合视图单元格中的自定义按钮选中和取消选中功能

How to handle Custombutton CheckedAnduncheck functionality in collectionviewcell in objective c with multiselection

我想要 collectionview 单元格,我在其中放置了用于将成员添加到 group.multiselection 的自定义按钮复选框也是 possible.but 当我 select 特定复选框与它一起时另一个复选框是不可见也是 selected,它与下面 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];
    }
}

`

该单元格可能正在重复使用。并且由于当单元格通过 cellForItemAtIndexPath 方法 returned 时您没有更新单元格,因此它们处于上次更新状态。解决方案:-

我假设您使用的是细胞信息模型

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

声明全局数组并初始化

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"];
  }
 }