我已经创建了带有导航栏和uicollectionView的视图控制器。UI集合视图包含自定义UICollectionViewCell。导航栏包含两个Uibarbutton项目,一个在左角 - 准备到上一页,另一个项目在右上角 - 安排在UI CollectionView中删除单元格,如下图:
:主屏幕
现在,我想在右上角的uibarbuttonitem时删除所选的uicollectionViewCell。
这是我的CellForiteMatindExpath方法的样子:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
self.GlobalIndexPath = indexPath;
MessagesCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"messagesCell" forIndexPath:indexPath];
cell.MessageHeading.text = [self.Message_Heading objectAtIndex:indexPath.row];
cell.MessageSubject.text = [self.Message_Subject objectAtIndex:indexPath.row];
cell.MessageContent.text = [self.Message_Details objectAtIndex:indexPath.row];
[cell.Checkbox setHidden:YES];
[cell.Checkbox setChecked:NO];
}
我尝试了一个解决方案,例如将IndexPath声明为全局变量,并在按下按下的按钮事件中使用:
@property (strong,nonatomic) NSIndexPath *GlobalIndexPath;
some other code .......
//When Bin Icon(UIBarButtonItem) Clicked
- (IBAction)DeleteMessages:(id)sender {
[self.view makeToast:@"You clicked delete button !"];
NSIndexPath *indexPath = [self.MessageCollectionView.indexPathsForVisibleItems objectAtIndex:0] ;
BOOL created = YES;
// how to get desired selected cell here to delete
MessagesCollectionViewCell *cell = [self.MessageCollectionView cellForItemAtIndexPath:self.GlobalIndexPath];
if([cell.Checkbox isHidden])
{
[cell setHidden:YES];
}
else{
[cell.Checkbox setChecked:NO];
[cell.Checkbox setHidden:YES];
}
}
这是不起作用的。
用于显示按照检查的UICollectionViewCell,我正在使用@chris Chris Vasselli的解决方案
请帮助我。提前致谢。
有几个步骤。首先,确定所选的IndexPath,但在运行该方法时不要假设有选择..
// in your button method
NSArray *selection = [self.MessageCollectionView indexPathsForSelectedItems];
if (selection.count) {
NSIndexPath *indexPath = selection[0];
[self removeItemAtIndexPath:indexPath];
}
还有两个步骤可以从收集视图中删除项目:从数据源中删除它们,并告诉视图已更改。
- (void)removeItemAtIndexPath:(NSIndexPath *)indexPath {
// if your arrays are mutable...
[self.Message_Heading removeObjectAtIndex:indexPath.row];
// OR, if the arrays are immutable
NSMutableArray *tempMsgHeading = [self.Message_Heading mutableCopy];
[tempMsgHeading removeObjectAtIndex:indexPath.row];
self.Message_Heading = tempMsgHeading;
// ...
为每个数据源数组做一个或另一个。最后一步是告知收集视图,即数据源已更改,并且必须自行更新。有几种方法可以做到这一点。最简单的是:
// ...
[self.MessageCollectionView reloadData];
或更优雅:
[self.MessageCollectionView deleteItemsAtIndexPaths:@[indexPath]];
} // end of removeItemAtIndexPath