【发布时间】:2015-01-16 06:55:41
【问题描述】:
我正在尝试实现 heightForRowAtIndexPath 并希望使用我已经布局的具有自动布局的原型单元来查找高度。我已经尝试了以下所有方法,但都没有给我单元格的实际高度。他们似乎在标签被换行之前给了我单元格的高度。
我知道我可以使用 NSString 方法来查找每个字符串的高度并以这种方式计算单元格的高度,但是如果我沿着这条路走,我基本上是在复制自动布局的功能,并且必须维护单元格的布局在两个地方。我真的很想避免这种情况,我假设我在这里遗漏了一些非常简单的东西。
我的原型单元格的高度在 IB 中设置为 67,而内容视图的高度在 IB 中设置为 66。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"in heightForRowAtIndexPath: %@", indexPath);
if (!self.prototypeCell)
{
self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:@"MessageCell"];
}
// set the text in the labels
[self configureCell:self.prototypeCell forIndexPath:indexPath isForOffscreenUse:YES];
[self.prototypeCell setNeedsLayout];
[self.prototypeCell layoutIfNeeded];
// this gives 58 regardless of the length of the text in my labels
CGSize contentViewSize = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
// this gives me 58.5 regardless of the length of text in my labels
CGSize cellSize = [self.prototypeCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return cellSize.height;
}
【问题讨论】:
-
你已经接近正确了!它可能会帮助您查看一个工作示例。 github.com/mattneub/Programming-iOS-Book-Examples/blob/master/… 这是可下载项目的一部分,因此您可以实际看到它的运行情况。
标签: ios interface-builder autolayout