UICollectionViewCell which resizes based on the content

I wanted to make a UICollectionViewCell which resizes itself based on the content in it (for now it has a UILabel which can have a text of varied length). There are some sollutions on the web but they do not work always.

Please help me find a sollution to this.

I have used an estimatedItemSize property for the layout of the collection view

ex:


viewDidLoad(){

collectionView.dataSource = self

collectionView.delegate = self

let layout = UICollectionViewFlowLayout()

layout.minimumInteritemSpacing = 5.0

layout.minimumLineSpacing = 5.0

layout.estimatedItemSize = CGSize(width: 30, height: 21)

/

collectionView.collectionViewLayout = layout

}


inside the :cellForItemAtIndexPath:


/

let screenSize: CGRect = UIScreen.mainScreen().bounds

let screenWidth = screenSize.width

let screenHeight = screenSize.height

let usableScreenWidth = screenWidth * 0.50

let maxLayoutWidthForLable = usableScreenWidth * (3.0/4.0)

let maxLayoutWidthForButton = usableScreenWidth * (1.0/4.0)

/

cell.labelView.preferredMaxLayoutWidth = maxLayoutWidthForLable

cell.buttonView.titleLabel?.preferredMaxLayoutWidth = maxLayoutWidthForButton

//just allowing the prefered sizes for the label and button


and on the storyboard the

button and the label are allowed to fill the prototype and the number of lines for the label is set to 0


Thanks

santosh

"You don't say what happens with the above. As in what is going wrong.


However, you shouldn't need the code in "cellForItemAtIndexPath". All you should need is to:


  1. set estimatedItemSize
  2. use autolayout for the contents of the cell
  3. fix either the width or the height using autolayout so the other dimension can vary. For example, if you always want the label to be one line, then fix the label & cell height using autolayout. The length will then automaticall vary based on the label contents.

Lastly, if you are using a standard UICollectionViewController in a storyboard, you don't need the viewDidLoad code. In IB, use the "user defined runtime attributes" on the CollectionViewLayout object and define "estimatedItemSize size {30,21}". The other properties in your viewDidLoad can also be set in the layout object of the storyboard.

This thread is helpful, because it saved me some time, in this living nightmare called XCode 8. I have nearly lost a client because of the massive delays in bringing product to market. I've been using contraints since they were introduced, and even with autolayout and constraints in place, XCode 8 still ruined nearly every scene I've built! I am reverting back to XCode 7.3. I can't waste anymore time dealing with having to rebuild my application UI's.

UICollectionViewCell which resizes based on the content
 
 
Q