【发布时间】:2015-01-01 22:35:39
【问题描述】:
我在 UITableView 中使用自动布局和大小类,单元格根据其内容自行调整大小。为此,我使用的方法是,对于每种类型的单元格,您保留该单元格的屏幕外实例并在其上使用 systemLayoutSizeFittingSize 来确定正确的行高 - 此方法在 this StackOverflow post 和 @987654322 中有很好的解释@。
在我开始使用尺码等级之前,这非常有效。具体来说,我在常规宽度布局中为文本的边距约束定义了不同的常量,因此 iPad 上的文本周围有更多空白。这给了我以下结果。
似乎新的一组约束得到遵守(有更多空白),但行高计算仍然返回与未应用特定于大小类约束的单元格相同的值。 屏幕外单元格中的某些布局过程没有考虑窗口的大小等级。
现在我认为这可能是因为屏幕外视图没有没有超级视图或窗口,因此在发生systemLayoutSizeFittingSize 调用时它没有任何大小类特征可以引用(尽管它似乎确实使用了调整后的边距约束)。我现在通过在创建 UIWindow 后将屏幕外大小调整单元添加为 UIWindow 的子视图来解决此问题,这会产生所需的结果:
这是我在代码中所做的:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let contentItem = content[indexPath.item]
if let contentType = contentItem["type"] {
// Get or create the cached layout cell for this cell type.
if layoutCellCache.indexForKey(contentType) == nil {
if let cellIdentifier = CellIdentifiers[contentType] {
if var cachedLayoutCell = dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell {
UIApplication.sharedApplication().keyWindow?.addSubview(cachedLayoutCell)
cachedLayoutCell.hidden = true
layoutCellCache[contentType] = cachedLayoutCell
}
}
}
if let cachedLayoutCell = layoutCellCache[contentType] {
// Configure the layout cell with the requested cell's content.
configureCell(cachedLayoutCell, withContentItem: contentItem)
// Perform layout on the cached cell and determine best fitting content height.
cachedLayoutCell.bounds = CGRectMake(0.0, 0.0, CGRectGetWidth(tableView.bounds), 0);
cachedLayoutCell.setNeedsLayout()
cachedLayoutCell.layoutIfNeeded()
return cachedLayoutCell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
}
}
fatalError("not enough information to determine cell height for item \(indexPath.item).")
return 0
}
向窗口添加不应该被绘制的视图对我来说似乎是一种 hack。 有没有办法让 UIViews 完全采用窗口的大小类,即使它们当前不在视图层次结构中? 或者我还缺少什么?谢谢。
【问题讨论】:
标签: ios uikit autolayout size-classes