gpt4 book ai didi

ios - 如何设置动态 UICollectionView 单元格高度?

转载 作者:可可西里 更新时间:2023-10-31 23:50:01 25 4
gpt4 key购买 nike

如何设置动态单元格高度?

我需要在这个方法中设置单元格大小:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 

我试着这样做:

cell.bounds = CGRect(x: cell.bounds.origin.x, y: cell.bounds.origin.y, width: width, height: height) 

但是我不能向下滚动...

我试试这个方法:

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

但是这个方法是先调用,然后再调用这个方法:

cell.bounds = CGRect(x: cell.bounds.origin.x, y: cell.bounds.origin.y, width: width, height: height) 

那么..如何改变单元格高度?

最佳答案

首先,按照正常设置。 (正常约束 [左、右、顶部、底部和高度] 和 UICollectionView 的 IBOutlet。

其次,为高度约束、顶部约束和底部约束制作IBOutlets。

第三,添加->

//these are the outlets I am naming generic names but name them what you wish

IBOutlet var collectionViewCellDynamicConstraint: NSLayoutConstraint!
IBOutlet var topConstraintDynamicConstraint: NSLayoutConstraint!
IBOutlet var bottomConstraintDynamicConstraint: NSLayoutConstraint!

//into viewDidLoad

collectionViewCell.addObserver(self, forKeyPath: "contentHeight", options:NSKeyValueObservingOptions.New, context: nil)

topConstraintDynamicConstraint.addObserver(self, forKeyPath: "contentTop", options:NSKeyValueObservingOptions.New, context: nil)

bottomConstraintDynamicConstraint.addObserver(self, forKeyPath: "contentBottom", options:NSKeyValueObservingOptions.New, context: nil)

//create this override func

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {



//try use this segment below as well but if it doesn't work then remove it and try run again

self.collectionViewCell.sizeThatFits()

//



self.collectionViewCellDynamicConstraint.constant = collectionViewCell.sizeThatFits(CGSizeMake(self.collectionViewCell.frame.size.width, CGFloat.max)).height

// set these values (below) to the space/value that you set them at normally. Often what is needed is a refresh after changing the height of the view/collectionViewCell

self.topSpaceOld.constant = 0.4

self.bottomSpaceOld.constant = 10


}




// you need to de-initialise them before you leave the view or else it will crash
deinit {
self.collectionViewCell.removeObserver(self, forKeyPath: "contentHeight")

self.topConstraintDynamicConstraint.removeObserver(self, forKeyPath: "contentTop"

self.bottomConstraintDynamicConstraint.removeObserver(self, forKeyPath: "contentBottom")
)



}

可能存在一些命名问题,但应该可以。此代码用于让 UITextView 在 ScrollView 内部工作以获得 View 的动态高度。应该是同一个概念。

关于ios - 如何设置动态 UICollectionView 单元格高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35058768/

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