CollectionView insde TableViewCell在iOS中无法正常工作

时间:2019-01-25 14:00:40

标签: ios swift uitableview uicollectionview autolayout

我正在开发的应用程序包含在UITableViewCell内部的UICollectionView。 但是发生的是,重新加载数据时,收集视图的单元格自动宽度无法正常工作。 这是屏幕截图。 enter image description here

这是一个代码。

@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])

但是即使我添加了此代码,它也不起作用。 谁能帮帮我吗? 谢谢。

1 个答案:

答案 0 :(得分:1)

删除此行:

flowlayout.estimatedItemSize = CGSize(width: 1, height: 25)

您还应该像这样在界面enter image description here Builder中设置cellSize: