gpt4 book ai didi

ios - UICollectionViewCell 和 UICollectionView 的高度相等

转载 作者:IT王子 更新时间:2023-10-29 05:21:07 26 4
gpt4 key购买 nike

我应该如何将 UICollectionView 中单元格的高度设置为等于 Collection View 的高度?下面的代码不起作用,因为此时 Collection View 高度未知,因为自动布局在这个阶段混淆了属性。它会导致单元格高度高于实际 Collection View 。

我将为解决此问题的答案增加 300 赏金!

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

return CGSize(width: 100, height: collectionView.frame.size.height)
}

2015-12-16 18:43:53.643 My-app[1055:434762] the behavior of the enter code hereUICollectionViewFlowLayout is not defined because: 2015-12-16 18:43:53.643 My-app[1055:434762] the item height must be less than the height of the UICollectionView minus the section insets top and bottom values, minus the content insets top and bottom values. 2015-12-16 18:43:53.643 My-app[1055:434762] Please check the values return by the delegate. 2015-12-16 18:43:53.644 My-app[1055:434762] The relevant UICollectionViewFlowLayout instance is , and it is attached to ; layer = ; contentOffset: {0, 0}; contentSize: {3087, 307}> collection view layout: . 2015-12-16 18:43:53.644 My-app[1055:434762] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.

基于 hannads 建议的解决方案。如果有更好的方法请告诉我

与属性(property)观察员建立属性(property)。

var myCollectionViewHeight: CGFloat = 0.0 {
didSet {
if myCollectionViewHeight != oldValue {
myCollectionView.collectionViewLayout.invalidateLayout()
myCollectionView.collectionViewLayout.prepareLayout()
}
}
}

重写这个方法(多次调用)

override func viewDidLayoutSubviews() {
myCollectionViewHeight = myCollectionView.bounds.size.height
}

然后我在我的委托(delegate)中有这个:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {            
return CGSize(width: 100, height: myCollectionViewHeight)
}

最佳答案

下面是我的做法。首先在 View Controller 中添加一个全局变量,用于存储 Collection View 的高度。在viewDidLayoutSubviews方法中,将此变量设置为collectionView的高度,如果改变了,调用方法使UICollectionView布局失效

collectionView.collectionViewLayout.invalidateLayout()

这将调用方法来设置 collectionView 单元格的大小,并在该方法中将单元格的高度设置为保存 collectionView 高度的全局变量。

注意:目前在我的手机上,没有测试这段代码。我可能错过了什么。

关于ios - UICollectionViewCell 和 UICollectionView 的高度相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34318837/

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