flow layout的動態cell高度
不固定寬度
- 程式碼設定estimatedItemSize
override func viewDidLoad() {
super.viewDidLoad()
let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.estimatedItemSize = CGSize(width: 100, height: 100)
}
- 設定cell的auto layout條件。
可能的錯誤: item的寬度太大。 the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
因此範例裡label的寬度條件設為 <=
結果
固定寬度
在storyboard設定cell裡label的寬度條件,priority設為999。
在cell的awakeFromNib調整label的寬度條件
class MyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var quoteLabel: UILabel!
@IBOutlet weak var labelWidthConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
self.labelWidthConstraint.constant = (UIScreen.mainScreen().bounds.width - 30)/2
}
}