0

When I try to get cell's intrinsicContentSize in function collectionView(_:didSelectItemAt:), the result is (-1, -1).

I am using flow layout with auto layout config of cell's subviews and did not implement collectionView(_:layout:sizeForItemAt:). Does anyone have ideas?

Edit:

the auto layout of cell has fixed width and height. I turned on self-sizing by setting estimatedItemSize and config the collectionView as following:

self.collectionView.delegate = self
self.collectionView.dataSource = self
if let layout = self.collectionView.collectionViewLayout as? 
    UICollectionViewFlowLayout {
        layout.estimatedItemSize = CGSize(width: 100, height: 100)
}

And I try to get the cell's intrinsicContentSize in:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    let size = cell?.intrinsicContentSize
}

which gives me (-1, -1) for size

Hamish
  • 78,605
  • 19
  • 187
  • 280
Desmond DAI
  • 485
  • 5
  • 13

1 Answers1

1

A UICollectionViewCell has no intrinsicContentSize. Why do you expect it to have one?

  • If you want to know what size the cell is at this moment, just ask for its bounds.size.

  • If you want to know what size the cell would take on if it were sized from inside by the autolayout constraints of its subviews, call systemLayoutSizeFitting(_:).

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Yes, I realised this after that. Actually I would like to implement an expandable and collapsable cell which contains labels when tapping, and just thought `intrinsicContentSize` can reveal the size that fits all labels with full content shown – Desmond DAI Feb 16 '17 at 05:57
  • Sounds to me like what you want is `systemLayoutSizeFitting(_:)`. Added that to my answer. – matt Feb 16 '17 at 15:04
  • Just realize you are the author of the book "iOS 10 programming" and I am studying on it~ So nice to meet you LOL @matt – Desmond DAI Feb 17 '17 at 06:54
  • 1
    Great but I don't seem to be helping you with _this_ question :( – matt Feb 17 '17 at 16:06
  • Yes you have helped me realize that `intrinsicContentSize` is designed for views like `UILabel` and given me the useful method `systemLayoutSizeFitting(_:)`. I realize I need to read more on Apple's programming guides. In before I thought they are a little bit verbose haha – Desmond DAI Feb 18 '17 at 03:02