【问题标题】:CollectionView insde TableViewCell not working correctly in iOSTableView Cell 中的 CollectionView 在 iOS 中无法正常工作
【发布时间】:2019-01-25 14:00:40
【问题描述】:

我正在开发包含 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])

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

【问题讨论】:

    标签: ios swift uitableview uicollectionview autolayout


    【解决方案1】:

    删除这一行:

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

    您还应该像这样在接口Builder 中设置cellSize:

    【讨论】:

    • 我尝试过这种方式,但 ui 看起来很糟糕,抱歉,您能告诉我如何将高度定义为 25 吗?
    • 看起来像这样。 imgur.com/a/p9r54xN你能告诉我如何看起来像以前的版本吗?
    • 你在用故事板吗?
    • 您是否在您的 collectionView 中设置了 cellSize ?
    • 抱歉,怎么办?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多