在我的应用程序中,我有一个集合视图,其中单元格水平自动调整大小。这是一些代码:
// called in viewDidLoad()
private func setupCollectionView() {
let cellNib = UINib(nibName: SomeCell.nibName, bundle: nil)
collectionView.register(cellNib, forCellWithReuseIdentifier: SomeCell.reuseIdentifier)
guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
flowLayout.itemSize = UICollectionViewFlowLayout.automaticSize
}
该单元格有 1 个视图,该视图具有高度约束。此视图子视图一个标签,该标签限制为 2 行,不受宽度限制。这里的想法是允许标签在 2 行中计算自己的宽度适合文本。
为了完成这项工作,我在单元类中添加了以下代码:
override func awakeFromNib() {
super.awakeFromNib()
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
contentView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: topAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
现在,它完美运行。单元格是 autosizng,scrollView 是水平滚动等。直到我reloadData()
至少调用一次。然后单元格的大小为 50x50,并且在我离开屏幕并再次返回之前不再自动调整大小。
你有什么想法为什么会发生?