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

时间:2016-10-16 08:52:42

标签: swift uicollectionviewcell uicollectionviewlayout

您好我正在尝试设置动态单元格的高度。

enter image description here

这是我的UICollectionViewCell

import UIKit
import Parse
import ActiveLabel
class UserShopDetailCell: UICollectionViewCell {

    @IBOutlet weak var postImg: UIImageView!

    @IBOutlet weak var likesLbl: UILabel!
    @IBOutlet weak var usernameLbl: UILabel!
    @IBOutlet weak var commentLbl: ActiveLabel!
    @IBOutlet weak var descriptionLbl: ActiveLabel!
    @IBOutlet weak var profileImg: UIImageView!
    @IBOutlet weak var timeLbl: UILabel!

    @IBOutlet weak var descriptionTop: NSLayoutConstraint!
    @IBOutlet weak var commentTop: NSLayoutConstraint!
    @IBOutlet weak var timeTop: NSLayoutConstraint!


    override func awakeFromNib() {



    }


}

它是collectionviewcontroller

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

    let cellsAcross: CGFloat = 3
    let spaceBetweenCells: CGFloat = 1
    let dim = (collectionView.bounds.width - (cellsAcross - 1) * spaceBetweenCells) / cellsAcross

    var width = 114.0


    if(isGridView==true){
        return CGSize(width: 114, height: 114)
    }
    else {



//I want set dynamic height...not constant values
        return CGSize(width: 375, height: 500)
    }


}




 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {



    if isGridView == false {

 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UserShopDetailCell", for: indexPath) as! UserShopDetailCell

... ..... ......

  let basicHeight = cell.frame.size.width + 23 + cell.usernameLbl.frame.height + 1 + cell.likesLbl.frame.height

            let bottomHeight = cell.timeTop.constant + cell.timeLbl.frame.height + 12

        var dynamicHeight = basicHeight + bottomHeight

         cell.frame.size.height = dynamicHeight
        cell.sizeToFit()
        cell.sizeThatFits(CGSize(width: 375, height: dynamicHeight))
        cell.contentView.sizeThatFits(CGSize(width: 375, height: dynamicHeight))


return cell
}

}

enter image description here

正如你所看到的......白色空间是500高度 - 动态高度。

我想最终从动态高度值设置单元格的高度。

但是当我设置CGSize时,当大于CGSize时,动态高度不起作用。

我如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

按照以下步骤在collectionview上创建自定义大小单元格。使用estimatedItemSize和auto layout创建单元格时无需使用sizeForItemAtIndexPath方法。

  1. 在collectionViewFlowlayout上设置estimatedItemSize
  2. 使用自动布局为collectionviewcell子类设置正确的约束
  3. 使用自动布局参考linktutorial如何使用自定义单元格

    这是Github项目链接