在 UITableView 的自定義 Cell 中包含 UITextView 時,若在 textViewDidEndEditing: 中向數據源數組重複添加對象,會導致 Cell 重複顯示、數據錯亂。
- (void)textViewDidEndEditing:(UITextView *)textView {
FeedbackQuestionDC *feedBack = [dataArray objectAtIndex:textView.tag];
feedBack.FeedbackQuestionDC_Answers = textView.text;
[dataArray addObject:feedBack]; // 錯誤:重複添加同一對象!
[myTableView reloadData];
}
feedBack 已經存在於 dataArray 中(通過 objectAtIndex: 獲取)addObject: 將同一對象再次添加到數組末尾reloadData 後,數據源包含重複對象,導致 Cell 重複feedBack.FeedbackQuestionDC_Answers = textView.text),無需重新添加- (void)textViewDidEndEditing:(UITextView *)textView {
FeedbackQuestionDC *feedBack = [dataArray objectAtIndex:textView.tag];
feedBack.FeedbackQuestionDC_Answers = textView.text;
// 移除錯誤行:[dataArray addObject:feedBack];
// 數據已在原對象中更新,直接刷新即可
[myTableView reloadData];
// 或局部刷新:[myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:textView.tag inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"FeedbackCell";
FeedbackCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[FeedbackCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
FeedbackQuestionDC *item = dataArray[indexPath.row];
cell.configureWithItem:item indexPath:indexPath];
cell.textView.tag = indexPath.row; // 設置 tag 識別行
cell.textView.delegate = self;
return cell;
}
// FeedbackCell.h
@interface FeedbackCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UILabel *label;
- (void)configureWithItem:(FeedbackQuestionDC *)item indexPath:(NSIndexPath *)indexPath;
@end
// FeedbackCell.m
- (void)configureWithItem:(FeedbackQuestionDC *)item indexPath:(NSIndexPath *)indexPath {
self.label.text = item.FeedbackQuestionDC_QuestionText;
self.textView.text = item.FeedbackQuestionDC_Answers;
self.textView.tag = indexPath.row;
}
dequeueReusableCellWithIdentifier: 並正確配置cellForRowAtIndexPath 中設置 textView.tag = indexPath.rowreloadRowsAtIndexPaths:withRowAnimation: 替代 reloadData 提升性能IQKeyboardManager 或手動監聽鍵盤通知調整內容邊距複雜表單頁面建議使用 UICollectionView 配合 UICollectionViewCompositionalLayout,支援自尺寸 Cell、更靈活的佈局與更好的性能。