该篇博客是在《iOS高级开发——CollectionView的动态增删cell及模型重构》的基础上继续进行开发的。在之前那篇博客中,我们实现了动态的增删cell,并且使用了模型Model进行重构。今天我们要实现的是动态修改cell中的描述文字,通过这个案例,我们能发现使用Model的好处。代码已经上传至:https://github.com/chenyufeng1991/CollectionView .中的“动态增加cell和section实现” 。
(1)我这里通过长按cell的操作,弹出输入对话框,然后输入修改的描述文字。CollectionView本身没有长按事件,我这里通过增加长按手势来实现。该功能在《iOS高级开发——CollectionView的cell长按事件实现》中也有说明。实现代码如下:
#pragma mark - 创建长按手势
- (void)createLongPressGesture{
//创建长按手势监听
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
initWithTarget:self
action:@selector(myHandleTableviewCellLongPressed:)];
longPress.minimumPressDuration = 1.0;
//将长按手势添加到需要实现长按操作的视图里
[self.collectionView addGestureRecognizer:longPress];
}- (void) myHandleTableviewCellLongPressed:(UILongPressGestureRecognizer *)gestureRecognizer {
CGPoint pointTouch = [gestureRecognizer locationInView:self.collectionView];
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
NSLog(@"长按手势开始");
NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:pointTouch];
if (indexPath == nil) {
NSLog(@"空");
}else{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入修改后的描述文字" preferredStyle:UIAlertControllerStyleAlert];
//以下方法就可以实现在提示框中输入文本;
[alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
UITextField *cellDescTextField = alertController.textFields.firstObject;
NSString *cellDesc = cellDescTextField.text;
NSLog(@"输入的文字是:%@",cellDesc);
//找到当前操作的section;
SectionModel *section = [self.dataSectionArray objectAtIndex:indexPath.section];
//找到当前操作的cell;
CellModel *cell = [section.cellArray objectAtIndex:indexPath.row];
//修改该cell的描述文字;
cell.cellDesc = cellDesc;
//确定当前的cell数组;
self.dataCellArray = section.cellArray;
//替换cell数组中的内容;
[self.dataCellArray replaceObjectAtIndex:indexPath.row withObject:cell];
//更新界面;
[self.collectionView reloadData];
}]];
[alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = @"请输入Section名称";
}];
[self presentViewController:alertController animated:true completion:nil];
NSLog(@"Section = %ld,Row = %ld",(long)indexPath.section,(long)indexPath.row);
}
}
if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
NSLog(@"长按手势改变,发生长按拖拽动作执行该方法");
}
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
NSLog(@"长按手势结束");
}
}
。
。
总结,我会持续对CollectionView的使用进行更新,并实现其他复杂实用的效果。请大家不断关注。
最近开源的iOS应用,高仿印象笔记 https://github.com/chenyufeng1991/iOS-Oncenote 。欢迎大家点赞并关注项目进度。也可以安装到手机上试玩哦。
github主页:https://github.com/chenyufeng1991 。欢迎大家访问!
iOS高级开发——CollectionView修改cell的文本及模型重构
原文:http://blog.csdn.net/chenyufeng1991/article/details/50148043