Reputation: 3772
I have a paging UICollectionView with horizontal FlowLayout inside a UIScrollView (more content above and below) that only shows one UICollectionViewCell at a time. Each cell has full width but dynamic height. Now I'd like to adjust the UICollectionView height whenever the cell is changed.
I already have a method that I call when the current or next "page" changes where I update the height constraint of the UICollectionView. It's already working if the next "page" is taller than the previous but it completely messes up when the next page is smaller than the current.
GIF of current state (too big to include)
private func updateCardHeight() {
guard let currentHeight: CGFloat = cardCollectionView.layoutAttributesForItem(at: currentIndexPath)?.frame.height,
let nextHeight: CGFloat = cardCollectionView.layoutAttributesForItem(at: nextIndexPath)?.frame.height
else { return }
let height = max(currentHeight, nextHeight)
guard cardsHeightConstraint.constant != height else { return }
cardsHeightConstraint.constant = height
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: [], animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
At some point the layoutAttributesForItem(at:)
fails and returns a fixed height of 50
instead of approx. 300
. Did anyone try something similar already - I couldn't find anything and am a bit lost.
Thanks for your help!
Upvotes: 1
Views: 365
Reputation: 1634
@Hannes, I saw problem in your project(the item height must be less than the height of the UICollectionView). There are various ways to achieve it but currently, I can suggest the minimal way to fix it. You could implement "UICollectionViewDelegateFlowLayout", and try this code:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return self.cardCollectionView.frame.size
}
Hope it helpful for you.
Upvotes: 1