如何使用iOS 8方法动态调整CollectionViewCell的大小

时间:2014-10-17 17:39:28

标签: ios swift uicollectionview

我试图在iOS 8上为selfView应用自行调整大小的单元格。但是,设置estimatedItemSize属性是不够的。我还实现了preferredLayoutAttributesFittingAttributes,但单元格似乎已关闭。

我错过了什么?

在我的ViewController中:

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        var flowLayout = collectionView.collectionViewLayout as UICollectionViewFlowLayout
        var width = collectionView.frame.width
        //where does this value come from? isn't this supposed to be dynamic now???
        flowLayout.estimatedItemSize = CGSizeMake(width, 100.0);
    }

细胞分类:

@IBOutlet var titleLabel: UILabel!
    @IBOutlet var starsView: HCView!
    @IBOutlet var starsSubtitle: UILabel!
    @IBOutlet var bodyLabel: UILabel!
    @IBOutlet var footerLabel: UILabel!
    @IBOutlet var line: UIView!

    //I thought we didn't need to implement anything else???? Why are we basically calculating the size for everything
    //If using autoLayout???
    override func preferredLayoutAttributesFittingAttributes(layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes! {

        var attr = layoutAttributes.copy() as UICollectionViewLayoutAttributes
        var bodySize = bodyLabel.sizeThatFits(CGSizeMake(CGRectGetWidth(layoutAttributes.frame), CGFloat.max))
        var titleSize = titleLabel.sizeThatFits(CGSizeMake(CGRectGetWidth(layoutAttributes.frame), CGFloat.max))
        var starsSubtitleSize = starsSubtitle.sizeThatFits(CGSizeMake(CGRectGetWidth(layoutAttributes.frame), CGFloat.max))
        var footerLabelSize = footerLabel.sizeThatFits(CGSizeMake(CGRectGetWidth(layoutAttributes.frame), CGFloat.max))

        var newFrame = attr.frame
        newFrame.size.height = bodySize.height + titleSize.height + starsSubtitleSize.height + footerLabelSize.height
        attr.frame = newFrame
        return attr
    }

单元格最终太短,并截断bodyLabel ......

0 个答案:

没有答案