我正在开发的应用程序包含在UITableViewCell内部的UICollectionView。 但是发生的是,重新加载数据时,收集视图的单元格自动宽度无法正常工作。 这是屏幕截图。
这是一个代码。
@IBOutlet weak var cv_inside: UICollectionView!
...
cv_inside.collectionViewLayout = AlignedCollectionViewFlowLayout(horizontalAlignment: .left, verticalAlignment: .top)
if let flowlayout = cv_inside.collectionViewLayout as? UICollectionViewFlowLayout {
flowlayout.estimatedItemSize = CGSize(width: 1, height: 25)
flowlayout.minimumLineSpacing = 10
}
cv_inside.isScrollEnabled = false
cv_inside.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.new, context: nil)
....
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
cv_inside.layer.removeAllAnimations()
heightOfCollectionViewConstant.constant = cv_inside.collectionViewLayout.collectionViewContentSize.height
UIView.animate(withDuration: 0.5) {
self.updateConstraints()
self.layoutIfNeeded()
}
}
在iOS 12之前运行良好,我研究必须添加此代码。
contentView.translatesAutoresizingMaskIntoConstraints = false
let leftConstraint = contentView.leftAnchor.constraint(equalTo: leftAnchor)
let rightConstraint = contentView.rightAnchor.constraint(equalTo: rightAnchor)
let topConstraint = contentView.topAnchor.constraint(equalTo: topAnchor)
let bottomConstraint = contentView.bottomAnchor.constraint(equalTo: bottomAnchor)
NSLayoutConstraint.activate([leftConstraint, rightConstraint, topConstraint, bottomConstraint])
但是即使我添加了此代码,它也不起作用。 谁能帮帮我吗? 谢谢。