UICollectionView - self sizing cells

Hi!

Yesterday I have started exploring the property called UICollectionViewFlowLayoutAutomaticSize,which can be used on IOS 10+ application to create self-sizing cells. So no more weird code, to achieve right cell sizing or hard-coded values. I have found Apple’s implementation weird. There is also not much samples available and nothing concrete in Apple’s docs, unless I missed something. Therefore I have prepared a simple demo and I would be grateful if we can together comment several things. The idea wanted to achieve is create self-sizing scrollable tabs with equal height, but different width.

Now to the weird things:

  • is it 100% right, to assign UICollectionViewFlowLayoutAutomaticSize as estimated size? The is the opposite of UITableView’s implementation where you define cell size as automatic, and estimatedSize as some estimate value. In all examples it is done as estimatedSize, but it feels weird

  • now even more weird part. If I defined the estimateSize as an automatic, why the do I need to implement following collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize and in it define size the same (for example) as the size of the collectionView, but in reality the items have defined size and custom width?!? Here my logic breaks. Can someone explain this behaviour?

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    /// WHY!?!?!? this works
    return CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height)
    }

I have prepared demo app, but I am not allowed to upload it. So here is the link: https://drive.google.com/file/d/1CM4Z_jJdgtoxfVCRoBDHW3TL4qLAxWIJ/view?usp=sharing

Hi @dobnik_leon,
Have you looked at the UILabel and autosizing? I found that using an UILabel to autosize will provide you fixed height and variable width. You can then use the dimensions of the label and set the frame of the Cell with the appropriate padding.

Have you tried to write the sizing code in

// MARK: - UICollectionViewDelegate

extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: 100)
    }
}

cheers,

Jayant

Hi - on my simulator - iPhone 8 Plus it does work.

I am well aware of option of using UILabel or event SizeForRect or using Medium articles of self sizing cells (solutions for iOS9). My goal is to achieve the same with that Apple’s introduced property.

This topic was automatically closed after 166 days. New replies are no longer allowed.