我做了一个像imessage这样的 View ,只是在底部的 TextView 中输入文本。我使用 TableView 来执行此操作,并在最后一个单元格中使用 TextView 。当我输入超过一行的长文本时,我需要 TextView 并且单元格变得更小。所以我需要刷新单元格的高度。但是如果我使用 TableView 的重新加载或重新加载行, TextView 中的内容将消失,键盘也会消失。有什么更好的方法来修复它吗?
也许我应该使用工具栏来轻松完成?但我仍然怀疑 TableView 能否做到这一点。
最佳答案
当您调用 beginUpdates
和 endUpdates
时,单元格会平滑地调整大小。在这些调用之后,tableView 将为表格中的所有单元格发送 tableView:heightForRowAtIndexPath:
,当 tableView 获得所有单元格的所有高度时,它将以动画方式调整大小。
并且您可以通过直接设置单元格的属性来更新单元格而无需重新加载它们。不需要涉及 tableView 和 tableView:cellForRowAtIndexPath:
要调整单元格的大小,您可以使用与此类似的代码
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];
CGSize size = // calculate size of new text
if ((NSInteger)size.height != (NSInteger)[self tableView:nil heightForRowAtIndexPath:nil]) {
// if new size is different to old size resize cells.
// since beginUpdate/endUpdates calls tableView:heightForRowAtIndexPath: for all cells in the table this should only be done when really necessary.
[self.tableView beginUpdates];
[self.tableView endUpdates];
}
return YES;
}
要在不重新加载的情况下更改单元格的内容,我使用这样的方法:
- (void)configureCell:(FancyCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
MyFancyObject *object = ...
cell.textView.text = object.text;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
FancyCell *cell = (FancyCell *)[tableView dequeueReusableCellWithIdentifier:@"CellWithTextView"];
[self configureCell:cell forRowAtIndexPath:indexPath];
return cell;
}
// whenever you want to change the cell content use something like this:
NSIndexPath *indexPath = ...
FancyCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
[self configureCell:cell forRowAtIndexPath:indexPath];
关于ios - 有什么方法可以在不重新加载/重新加载行的情况下刷新单元格的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14066537/