我在我的应用中实现了一个集合视图。
收集单元格包含一个名为项目删除按钮的按钮。 删除项目后,标签不会更新,因此,如果我删除了第二项,那么它将删除它旁边的标签。
我的代码如下:
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"GradientCell";
UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
UIButton *btn_close=[UIButton buttonWithType:UIButtonTypeCustom];
[btn_close setFrame:CGRectMake(50, 00, 18, 18)];
[btn_close setBackgroundImage:[UIImage imageNamed:@"close.png"] forState:UIControlStateNormal];
[btn_close addTarget:self action:@selector(delete_image:) forControlEvents:UIControlEventTouchUpInside];
btn_close.tag=indexPath.row;
return cell;
}
-(void)delete_image:(UIButton*)sender
{
[self.col_view performBatchUpdates:^{
[arr_images removeObjectAtIndex:sender.tag];
NSIndexPath *indexPath =[NSIndexPath indexPathForRow:sender.tag inSection:0];
[self.col_view deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
} completion:^(BOOL finished) {
}];
}
答案 0 :(得分:2)
简单的答案是不要将行用作标签!!
您应该在“标记”中保存任何其他信息,以后可以将其转换为行号。例如,您可以将图像保存在'arr_images'中,理想情况下,您应该存储指向该单元格所代表的对象的指针。
当您想要删除对象时,您应该使用该对象重新构建索引路径
xxxx = [arr_images indexOfObject:sender.tag];
NSIndexPath *indexPath =[NSIndexPath indexPathForRow:xxxx inSection:0];
[self.col_view deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];