問題
UICollectionViewFlowLayoutのestimatedItemSizeに以下を設定する。
if let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = CGSize(width: 1, height: 1)
}
もしくは
if let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
本来有効になるUICollectionViewCellのSelf-Sizing CellsがiOS12未満だと問題ないが、iOS12ではうまく動かない。
対応
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak internal var label: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.contentView.translatesAutoresizingMaskIntoConstraints = false
let leftConstraint = self.contentView.leftAnchor.constraint(equalTo: self.leftAnchor)
let rightConstraint = self.contentView.rightAnchor.constraint(equalTo: self.rightAnchor)
let topConstraint = self.contentView.topAnchor.constraint(equalTo: self.topAnchor)
let bottomConstraint = self.contentView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
NSLayoutConstraint.activate([leftConstraint, rightConstraint, topConstraint, bottomConstraint])
}
}
UICollectionViewCellのawakeFromNib()で上記の設定を行うことでうまく動作するようになる。