我有UITableView
,并且手动调整了UITableViewCells
的大小。每个UITableViewCell
包含UITextView
。当添加新文本时,如果文本将从键盘上隐藏,则单元格会增大,并且在删除时会缩小,并且tableview会上升。通过返回键添加新行时除外。然后它有时可以正常工作,但是在几行新的行之后(计数不同-可以是2,可以是16),单元格只是停止增长,而当表视图上升时,它仅在底部留有空间。如果然后关闭键盘,则将正确地重新计算单元格大小,并在其中显示新行。使用其他文本不会发生此问题。然后,单元格增长,表格视图按预期方式上升。任何想法和/或解决方法将不胜感激。
编辑:经过更多测试,我发现如果在文本视图中粘贴大量文本,因此它不仅与新的换行字符相连,还会发生此问题
我用来更新textviews的代码是:
在单元格中:
-(void)textViewDidChange:(UITextView *)textView {
dispatch_async(dispatch_get_main_queue(), ^{
[UIView setAnimationsEnabled:NO];
[self.textViewUpdaterDelegate didChangeTextViewForCell:self];
[UIView setAnimationsEnabled:YES];
});
}
然后在代表中:
- (void)didChangeTextViewForCell:(nonnull SectionQuestionCell *)cell {
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:cell.center];
NSInteger index = indexPath.row;
Question *question = self.questions[index];
question.hint = cell.dataTextView.text;
//to update the table view cell height
[self.tableView beginUpdates];
[self.tableView endUpdates];
CGRect cursor = [cell.dataTextView caretRectForPosition:cell.dataTextView.selectedTextRange.start];
CGRect convertedCursor = [cell.dataTextView convertRect:cursor toView:self.tableView.superview];
CGFloat allHeight = self.tableView.superview.frame.size.height;
CGFloat cursorEnd = convertedCursor.origin.y + convertedCursor.size.height;
CGFloat visibleHeight = allHeight - self.keyboardHeight;
if (visibleHeight >= cursorEnd && cursorEnd > 0) {
//it means it is in the visible part
return;
}
CGFloat difference = 0;
if (cursorEnd >= 0) {
difference = cursorEnd - visibleHeight;
} else {
difference = -convertedCursor.origin.y;
}
if (indexPath.row == self.questions.count - 1 && self.tableView.contentSize.height > self.tableView.frame.size.height) {
[self.tableView beginUpdates];
[self.tableView endUpdates];
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
} else if (difference != 0) {
[UIView animateWithDuration:0.3 animations:^{
self.tableViewTopConstraint.constant -= difference;
}];
}
}