如何创建动态UICollectionView项目大小?

时间:2015-10-12 01:16:07

标签: ios swift uicollectionview uicollectionviewcell

我一直在研究这个问题大概24小时了,我似乎无法了解Apple如何设定CollectionViewCell的动态高度。

这是我完全迷失的地方:

1。)我需要在我的UICollectionView中每个Cell的帧大小由每个单元格中的UILabel文本确定。 UILabel的框架被限制在单元格的边缘,因此只需抓住UILabel.frame的高度就可以得到我需要的精确值。

2。)1 BIG PROBLEM,UICollectionView的sizeForItemAtIndexPath函数在UILabels甚至填充在UICollectionView的cellForItemAtIndexPath函数之前首先执行。

下面是我试过的黑客攻击失败:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MsgCell", forIndexPath: indexPath) as! CustomCollectionViewCell

    cell.txtLabel.text = dummyChatFeed[indexPath.row].messageBody   
    cell.txtLabel.sizeToFit()
    cell.lineBreakMode = NSLineBreakMode.ByWordWrapping

    // store the value of this proper label height back into the array:
    dummyChatFeed[indexPath.row].frameHeight = cell.txtLabel.frame.height
    return cell
}

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

    // grab that proper label height again:
    var theHeightThatFits = dummyChatFeed[indexPath.row].frameHeight

    return CGSize(width: Double(self.view.frame.width), height: Double(theHeightThatFits))
}

dummyChatFeed是一个NSObject类,它只包含这4个属性:

var messageBody = ""
var author = ""
var frameHeight = CGFloat(0)
var indexPathRow = 0

我尝试过的这个解决方案几乎没有用,而且因为Cell的高度取决于它内部的标签所以它很糟糕。但是从这里出发的最佳方式是什么?

我最初认为最好保留一个对象数组,该对象具有存储标签文本的对象的一个​​属性,而对象的另一个属性应该存储推荐高度的值,但我刚刚学到了很难的方法它永远不会起作用。

我是否想以编程方式在dummyChatFeed中声明UILabel并根据文本和字体计算其宽度和高度?

我需要我的应用程序向后兼容iOS 8.4,所以我不能使用UIStackViews。

0 个答案:

没有答案
相关问题