简体   繁体   English

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

[英]CollectionView insde TableViewCell not working correctly in iOS

I'm developing app which contains UICollectionView inside UITableViewCell. 我正在开发在UITableViewCell内包含UICollectionView的应用程序。 But what happens is that collection view's cell auto width is not working correctly when reloading data. 但是发生的是,重新加载数据时,收集视图的单元格自动宽度无法正常工作。 Here's a screenshot. 这是屏幕截图。 在此处输入图片说明

Here's a code. 这是代码。

@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()
    }
}

It worked fine before iOS 12 and I researched that I have to add this code. 在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])

But even I added this code, it doesn't work. 但是,即使我添加了此代码,它也不起作用。 Can anyone please help me? 谁能帮帮我吗? Thanks. 谢谢。

Remove this line : 删除此行:

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

you should also set cellSize in Interface 您还应该在接口中设置cellSize 在此处输入图片说明 Builder like this: 像这样的生成器:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM