問題
需求:
1.項目中UITableView
的cell嵌套了UITextView
2.根據(jù)UITextView
里面的文字的長度自動適應高度
這就難免使用UITableView
的- (void)reloadData;
或者是- (void)reloadRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
但是非常不幸
一調(diào)用- (void)reloadData;
會調(diào)用resignFirstResponder
會導致鍵盤的退出,給用戶造成非常不好的體驗.
解決方法:
使用
[self.tableView beginUpdates];
[self.tableView endUpdates];
來替換 reloadData
可以完美調(diào)用-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
,但是不引發(fā)resignFirstResponder
最后附上部分示例代碼:
WEAK_OBJECT(model);
cell.textViewTextChanged = ^(NSString *text, UITextView *sender) {
STRONG_OBJECT(model);
CGFloat width = (SCREEN_WIDTH - 20 - 100);
CGFloat height = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: FONT(14)} context:nil].size.height;
model.key_value = text;
if (self.preViewH != ceil(height)) {
self.preViewH = ceil(height);
//原先使用
// [self.tableView reloadData];
//替換成
[self.tableView beginUpdates];
[self.tableView endUpdates];
}
};