Last active
December 8, 2021 15:12
-
-
Save philosopherdog/b27b8f51e39fb06cd177567b538a964d to your computer and use it in GitHub Desktop.
Auto Sizing Cells
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
extension UICollectionReusableView { | |
/** | |
Used for creating dynamic height cells | |
- Call from overridden UICollectionReusableView (Cell) method `preferredLayoutAttributesFitting(_:)` which the system calls | |
- Setup the cell width in `sizeForItem` as usual & pass a temp height | |
- Setup Autolayout on cells to ensure a height can be computed | |
- Parameter UICollectionViewLayoutAttributes: pass from overridden method | |
- Returns: `UICollectionViewLayoutAttributes` | |
*/ | |
func handlePreferredLayoutAttributesFitting( | |
_ layoutAttributes: UICollectionViewLayoutAttributes | |
) -> UICollectionViewLayoutAttributes { | |
setNeedsLayout() | |
layoutIfNeeded() | |
// should work on both headers/footers and plain cells | |
let v = (self as? UICollectionViewCell)?.contentView ?? self | |
let size = v.systemLayoutSizeFitting(layoutAttributes.size) | |
var newFrame = layoutAttributes.frame | |
newFrame.size.height = ceil(size.height) | |
layoutAttributes.frame = newFrame | |
return layoutAttributes | |
} | |
/* | |
I also set this (but probably isn't required) | |
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize | |
*/ | |
extension OrderDetailsViewController: UICollectionViewDelegateFlowLayout { | |
func collectionView( | |
_ collectionView: UICollectionView, | |
layout collectionViewLayout: UICollectionViewLayout, | |
sizeForItemAt indexPath: IndexPath | |
) -> CGSize { | |
// 100 height is just a temporary value | |
.init(width: collectionView.bounds.width, height: 100) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment