UITableView 内で Auto Layout クラスと size クラスを使用しており、セルの内容に基づいてセルサイズが自動的に調整されます。このために、セルの種類ごとに、そのセルのオフスクリーン インスタンスを保持し、それを使用してsystemLayoutSizeFittingSize
正しい行の高さを決定する方法を使用しています。
サイズクラスを使い始めるまで、これはうまくいきました。具体的には、Regular Width レイアウトのテキストの余白制約にさまざまな定数を定義したため、iPad ではテキストの周囲に余白が多くなります。これにより、次の結果が得られます。
新しい一連の制約が適用されているように見えますが (余白が増えています)、行の高さの計算では、サイズ クラス固有の制約が適用されなかったセルの場合と同じ値が返されます。オフスクリーン セルのレイアウト プロセスの一部で、ウィンドウのサイズ クラスが考慮されていません。
これはおそらく、オフスクリーン ビューにスーパービューやウィンドウがなく、呼び出しが発生した時点で参照するサイズ クラスの特性がないためだと考えましたsystemLayoutSizeFittingSize
(ただし、調整された制約を使用しているように見えますが、余白)。オフスクリーン サイズ変更セルを作成後に 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
}
描画されるはずのないビューをウィンドウに追加することは、私にはハックのように思えます。現在ビュー階層にない場合でも、UIViews にウィンドウのサイズ クラスを完全に採用させる方法はありますか? それとも、私が見逃しているものがありますか?ありがとう。