我有一个UITableViewCell
,里面有一个标签。我想根据它里面的内容计算单元格大小。
我不只是在内容视图中设置约束,我还为封闭的UITableViewCell添加了约束:
+--------------------------+
|UITableViewCell |
| | inset |
| +------------------+ |
| |contentView | |
| | |inset | |
| | +------------+ | |
|-- |--| Label |--| --|
| | +------------+ | |
| | |inset | |
| +------------------+ |
| |inset |
+--------------------------+
以下是计算大小的代码:
override public class func cellSize(item: ItemInterface?, fittingSize: CGSize) -> CGSize {
struct Static {
static var onceToken : dispatch_once_t = 0
static var sizingCell : LabelTableViewCell!
}
dispatch_once(&Static.onceToken, {
Static.sizingCell = NSBundle.mainBundle().loadNibNamed("LabelTableViewCell", owner: self, options: nil)[0] as! LabelTableViewCell
})
let sizingCell = Static.sizingCell
// sets the text of the label and also adds constraints
// from label to enclosing content view
sizingCell.setupCell(text: "asdkfjklsd")
// for multi line support
sizingCell.label.preferredMaxLayoutWidth = fittingSize.width
// update all the constraints
sizingCell.setNeedsUpdateConstraints()
sizingCell.updateConstraintsIfNeeded()
// re-layout cell
sizingCell.setNeedsLayout()
sizingCell.layoutIfNeeded()
// calculate size for the whole cell (not just contentView)
let size = sizingCell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
return CGSizeMake(size.width, size.height)
}
我最终得到的是一个被压扁的细胞。标签最终太小,因此你几乎看不到标签: