SeeMeCode
SeeMeCode

Reputation: 1435

How do I set a different height for each UICollectionViewCell

I feel like this should be a lot easier than it is. All I want to do is have a different height for each of my collection view's cells (depending on the size of the label inside each cell). I'm using sizeForItemAtIndexPath, but the trouble is figuring out the height before the cell is created.

What I have now:

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

    // target width of each cell - widht of the collectionView
    let targetWidth: CGFloat = collectionView.frame.width - 20.0

    // setup a prototype cell
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCustomCellIdentifier", forIndexPath: indexPath) as! MyCustomCell

    // for the sake of simplicity, let's just assume data is coming from somewhere else
    cell.nameLabel.text = data.name
    cell.notesLabel.text = data.notes

    // resize - layoutSubviews in LocationCell controller
    cell.layoutIfNeeded()

    // get the size based on constraints
    var size = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)

    // force width
    size.width = targetWidth

    return size
}

What's not working is dequeueReusableCellWithReuseIdentifier. I'm guessing it's because the UICollectionViewCell is not yet available? I also tried registerClass to get that, but that doesn't seem to work either. :(

Is there an easier way to do this entirely? All I need to do is figure out what the height is for the cell before it's created. I need an instance of the UICollectionViewCell subclass in order to even be able to start (so I can actually access the label and try to determine a height). Been stuck on this for hours. :/

Upvotes: 0

Views: 737

Answers (2)

Sourav Gupta
Sourav Gupta

Reputation: 762

Use this method

 func heightForComment(comment:NSString,font: UIFont, width: CGFloat) -> CGFloat {
        let rect = NSString(string: comment).boundingRectWithSize(CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        return ceil(rect.height)
}

Upvotes: 1

Francisco Escobar
Francisco Escobar

Reputation: 241

This is not the proper way to do this, but works for me

use this function to obtain the size of the text

func labelSize(texto: NSString) -> CGRect {
        var atributos = [NSFontAttributeName: UIFont.systemFontOfSize(17)]
        var labelSize = texto.boundingRectWithSize(CGSizeMake(280, CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: atributos, context: nil)
        return labelSize
    }

Upvotes: 1

Related Questions