ale00 ale00 - 3 months ago 226
Swift Question

How can I automatic size Collection View cell containing text in iOS 10

I want to make a Collection View like the one made by Apple in this video (https://developer.apple.com/videos/play/wwdc2016/219/?time=1500) where each cell contains a word of a text in a UILabel, like in the following image.

In the video they use the new

UICollectionViewFlowLayoutAutomaticSize
constant for
estimatedItemSize
.
Collection View with text

What is the best way to do this in iOS 10? How can I use
UICollectionViewFlowLayoutAutomaticSize
with Storyboard?

Answer

You have to create your own subclass of UICollectionViewFlowLayout and set the Flow Layout object of your Collection View in your Storyboard to this custom class, then write this code in your custom class:

override init() {
    super.init()
    estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

Obviously you have to set the target of your app to iOS 10