该篇博客是在《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];
- }
(2)然后需要在长按开始的方法内弹出输入对话框,在点击对话框确定按钮的时候进行修改文本。实现代码如下:
- - (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);
-
-
-
- SectionModel *section = [self.dataSectionArray objectAtIndex:indexPath.section];
-
- CellModel *cell = [section.cellArray objectAtIndex:indexPath.row];
-
- cell.cellDesc = cellDesc;
-
-
- self.dataCellArray = section.cellArray;
-
- [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(@"长按手势结束");
- }
- }
(3)实现效果如下:
![](https://img-blog.csdn.net/20151202145715342?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
。
。
总结,我会持续对CollectionView的使用进行更新,并实现其他复杂实用的效果。请大家不断关注。
最近开源的iOS应用,高仿印象笔记 https://github.com/chenyufeng1991/iOS-Oncenote 。欢迎大家点赞并关注项目进度。也可以安装到手机上试玩哦。
github主页:https://github.com/chenyufeng1991 。欢迎大家访问!