Saturday, 2 June 2018

UICollectionViewFlowLayout cell size never changes despite sizeForItemAt implemented

I have a UICollectionViewCell that has a UICollectionView with UICollectionViewFlowLayout inside. I am making the cell the delegate and the datasource of the collection view. I am conforming to UICollectionViewDelegateFlowLayout and implementing collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize (and returning the correct size).
However, when I call layout.itemSize.height I get the default height, 50.
class MyCell: UICollectionViewCell {
  fileprivate lazy var collectionView: UICollectionView = {
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: 
UICollectionViewFlowLayout())
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.register(SomeOtherCell.self, forCellWithReuseIdentifier:
 SomeOtherCell.reuseIdentifier)
    collectionView.showsHorizontalScrollIndicator = false
    collectionView.showsVerticalScrollIndicator = false
    return collectionView
  }()

  fileprivate lazy var layout: UICollectionViewFlowLayout? = {
    let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout
    layout?.scrollDirection = .horizontal
    layout?.sectionInset = UIEdgeInsets.zero
    return layout
  }()

  override func sizeThatFits(_ size: CGSize) -> CGSize {
  collectionView.frame = CGRect(x: layoutMargins.left, y: origin.y,
 width: width, height: layout.itemSize.height)
  // layout.itemSize.height is always 50
  }
}
extension MyCell: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, 
layout collectionViewLayout: UICollectionViewLayout, 
sizeForItemAt indexPath: IndexPath) -> CGSize {
    guard tags.count != 0 else {
        return .zero
    }

    let tag = Tag(text: tags[indexPath.item], index: indexPath.item)
    placeholderCell.configure(with: tag)
    let size = placeholderCell.getFrame(at: .zero, 
fitting: placeholderCell.width, alignedBy: semanticContentAttribute, 
apply: false).size
    collectionViewWidth += size.width
  // this size is always correct, that's what I want when I call 
 layout.itemSize.height 
    return size
  }
}



from UICollectionViewFlowLayout cell size never changes despite sizeForItemAt implemented

No comments:

Post a Comment