【发布时间】:2014-02-19 16:32:58
【问题描述】:
关于 SO 的问题有十几个类似的问题,但似乎没有就最佳方式达成共识。此外,我还没有找到任何适合我的解决方案。我的自定义 UITableViewCell 的不同之处在于我有两个标签,其中一个在它自己的视图中,还有一个文本视图。这三个都应该扩展到它们的内容。
我想知道是不是我的约束设置不正确,但我不确定我会调整什么。
这是我在 IB 的牢房。
内容视图是浅红色的,顶部的额外视图是白色的,里面有一个标签。
当文本更改时,我保存文本并更新tableView:
-(void)textViewDidChange:(UITextView *)textView
{
NSLog(@"row: %i", textView.tag);
[self.textStrings setObject:textView.text atIndexedSubscript:textView.tag];
[self.tableView beginUpdates];
[self.tableView endUpdates];
}
对于tableView:heightForRowAtIndexPath: 方法,我使用缓存的高度值(选定行除外)。在这种情况下,我将创建一个新单元格,对其进行配置,并使用systemLayoutSizeFittingSize: 获取高度。这似乎是最常见的solution。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// use cached height if there is one (and it isn't the selected row)
if ([self.selectedRow integerValue] != indexPath.row && indexPath.row < [self.rowHeights count]){
return [[self.rowHeights objectAtIndex:indexPath.row] floatValue];
}
static NSString *CellIdentifier = @"RMTextViewCell";
RMTextViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
[self configureCell:cell forIndexPath:indexPath];
[cell layoutIfNeeded];
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
height += 1; // add 1 for border
NSNumber *h = @(height);
[self.rowHeights setObject:h atIndexedSubscript:indexPath.row];
return height;
}
textView 确实展开了,但是当它进入多行时,顶部标签开始被剪裁。在某些版本中,当文本更改时,我已经让 textView 开始剪切/扩展。似乎自动布局不确定如何正确计算单元格的高度。
有什么想法吗?
这是我的Github project,里面有一些实验。重要文件是ViewControllers/RMTextViewTableViewController 和Cell/RMTextViewCell。如果您运行它,请查看“带文本的动态单元格”。
【问题讨论】:
标签: ios objective-c uitableview