1

I have a UICollectionView with a cell only contain of one label. I've implemented it working fine, but some string values set to label inside cell cut out. Check below image.

enter image description here

Select cell should display as "Day Before Yesterday". If there's a way to adjust cell width base on data length I can fix this. is it possible ?

PS: some similar questions suggested below method. so I've tried it but no luck.

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

        if(collectionView == dateRangeCollectionView){
            return (dateRanges[indexPath.item] as NSString).size(attributes: nil)
        }else{
            return (OrderStatus[indexPath.item] as NSString).size(attributes: nil)
        }
    }

I don't think this method even exist in swift 4. when I start to type "sizeForItemAt" Xcode didn't suggest this method.

  • https://developer.apple.com/documentation/uikit/uicollectionviewdelegateflowlayout/1617708-collectionview that's the one in the doc, check if it's the same. It's a delegate method, so be sure that you set it correctly to be even called. – Larme Oct 22 '17 at 10:42
  • I've implemented collection view correctly which is why collection view works fine. But I don't know why Xcode not suggesting that method when typing. I still have this problem to fix. – Chathuranga Shan Jayarathna Oct 22 '17 at 10:57
  • Did you set your class conforming to `UICollectionViewDelegateFlowLayout`? Did you set the delegate then of your collectionView Layout? – Larme Oct 22 '17 at 11:13

2 Answers2

0

To calculate the size of each cell, you will need to figure out the width that the text would take, also accounting for the padding given. Use this to get the width of the cell, and return the value in the sizeForItem delegate.

func labelSizeWithString(text: String,fontSize: CGFloat, maxWidth : CGFloat) -> CGRect{
let font = UIFont.systemFontOfSize(fontSize)
let label = UILabel(frame: CGRectMake(0, 0, maxWidth, CGFloat.max))
label.numberOfLines = 0
label.font = font
label.text = text

label.sizeToFit()

return label.frame

}

If you want the text to appear in one or two lines, use the option for numberOfLines. For the width you get, add in the appropriate padding value.

Rakshith Nandish
  • 599
  • 3
  • 13
0

Please use Self Sizing Cells. Follow the below steps for more informaton

Self sizing cells are only supported with flow layout so make sure thats what you are using.

Follow the following steps :

  1. Set estimatedItemSize on UICollectionViewFlowLayout

  2. Add support for sizing on your cell subclass (Autolayout). More info here.

Checkout this github repo : SelfSizingCollectionViewCell

Deep Moradia
  • 126
  • 5