本篇是〈CollectionView 的動態增刪 cell 及模型重構〉的延續。在前一篇中,我們實現了動態增刪 cell,並以 Model 進行重構;這次要挑戰的目標,是動態修改 cell 中的描述文字。透過這個案例,你會深刻體會到使用 Model 重構所帶來的巨大好處。
完整程式碼已上傳至 GitHub:https://github.com/chenyufeng1991/CollectionView,可參考其中的「動態增加 cell 和 section 實現」。
由於 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) {
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 = @"請輸入描述文字";
}];
[self presentViewController:alertController animated:true completion:nil];
}
}
}
在這段邏輯中,關鍵在於先依 indexPath.section 找到對應的 SectionModel,再依 indexPath.row 找到 CellModel,直接修改其屬性後刷新界面。這正是模型重構帶來的優勢——資料與視圖分離,修改邏輯變得清晰而可靠。


總結來說,我會持續更新 CollectionView 的相關用法,並實現更多複雜而實用的效果,敬請期待。