gpt4 book ai didi

ios - 限制 UICollectionView 高度以匹配内容的高度

转载 作者:搜寻专家 更新时间:2023-11-01 06:57:46 26 4
gpt4 key购买 nike

我有一个使用 UICollectionViewFlowLayout 的 UICollectionView。滚动方向是垂直的,但我只有少量(可变)单元格,不需要或不想滚动。 Collection View 顶部、前导和尾随被限制到父 View 。我试图让 Collection View 高度适合其内容。

如果我使用这个,初始高度看起来是正确的:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var collection: UICollectionView!
var heightConstraint: NSLayoutConstraint!

override func loadView() {
super.loadView()
self.collection = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
self.collection.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.collection)
// ...
self.collection.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
self.collection.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor).isActive = true
self.collection.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor).isActive = true

// Create placeholder constraint
self.heightConstraint = self.collection.heightAnchor.constraint(equalToConstant: 1)
self.heightConstraint.isActive = true
}

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
// Update placeholder constraint
self.heightConstraint.constant = self.collection.contentSize.height
}

// ...
}

但是当内容布局发生变化时,例如设备方向发生变化,这不会更新 Collection View 的高度。有没有办法在内容布局发生变化时更新约束常量?或者使用动态约束而不是常量的方法?

Swift 4.2,Xcode 10.0,目标 iOS 12。

最佳答案

更新约束的更好位置是 viewDidLayoutSubviews,它会在每次重新布局(方向更改、大小更改等)后调用。此外,向 Collection View 布局询问内容大小更可靠:

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()

// Update placeholder constraint
self.heightConstraint.constant = self.collection.collectionViewLayout.collectionViewContentSize.height
}

关于ios - 限制 UICollectionView 高度以匹配内容的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52463609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com