Self-sizing Cell

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014084081/article/details/85341562

Self-sizing Cell

在当前的项目中有许多动态高度的Cell,通过数据源来计算高度,一直在考虑能不能自动计算高度,在以前的项目中,有使用xib布局cell,可以自动的计算高度,但与Self-sizing Table View Cells一文介绍的方式,还是有点区别

Intrinsic Content Size

Views with Intrinsic Content Size一文中有如下的描述:

The following recipes demonstrate working with views that have an intrinsic content size. In general, the intrinsic content size simplifies the layout, reducing the number of constraints you need. However, using the intrinsic content size often requires setting the view’s content-hugging and compression-resistance (CHCR) priorities, which can add additional complications.
intrinsic内容大小可以简化布局,减少所需的约束。然而,使用intrinsic content size,通常要设置view的content-hugging和compression-resistance(CHCR),这样会增加复杂度

Setting a higher priority on content hugging means that the view will resist growing larger than its intrinsic size
设置content-hugging的优先级更高,表示view将会抵制增长的比它的intrinsic content size大
Setting a vertical content hugging priority tells Xcode which view to expand if it needs to fill the space
设置垂直方向的 content hugging 优先级,表示xcode会决定哪个view来填充剩余的空间

content hugging可理解为抵抗拉伸的能力,越高越不会被被拉伸
compression-resistance可理解为抵抗压缩的能力,越高越不会被压缩

可以将intrinsic content size理解为,view"希望"的大小。例如,对弈Label来说,就是给定font后渲染的size。对Image来说,就是image自身的大小

一个view的intrinsic content size,可以作为隐式的width和height约束。所以如果你不显式的指定width,即为隐式的width

iOS UIKit: What is intrinsic content size中,如下创建view的intrinsic content size:

override var intrinsicContentSize: CGSize {
   return CGSize(width: cornerRadius * 4, height: cornerRadius * 2)
}

如何实现self-sizing cell

1.使用Auto Layout布局UI元素
2.设置rowHeightUITableViewAutomaticDimension
3.设置estimatedRowHeight属性,或者实现估算高度的代理方法

需要注意约束的完整性:

  • 即每个子view的每个边都有约束
  • 是否存在从contentView的顶部到底部的约束
  • 约束没有冲突,没有错误

例子可以参考:

第三方实现:

Dynamic Type

参考:

猜你喜欢

转载自blog.csdn.net/u014084081/article/details/85341562