Skip to content

Instantly share code, notes, and snippets.

@dirtyhenry
Created October 19, 2017 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dirtyhenry/1820b9cb07095c42f427e38a912477d4 to your computer and use it in GitHub Desktop.
Save dirtyhenry/1820b9cb07095c42f427e38a912477d4 to your computer and use it in GitHub Desktop.
Definitive UICollectionViewCell dynamic size
class FooCell: UICollectionViewCell {
private var sizingOnlyWidthConstraint: NSLayoutConstraint? = nil
func sizeWith(width: CGFloat, myString: String) -> CGSize {
if sizingOnlyWidthConstraint == nil {
sizingOnlyWidthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: width)
sizingOnlyWidthConstraint?.isActive = true
}
if sizingOnlyWidthConstraint!.constant != width {
sizingOnlyWidthConstraint?.constant = width
}
self.commentBody = commentBody
return self.systemLayoutSizeFitting(UILayoutFittingCompressedSize,
withHorizontalFittingPriority: UILayoutPriorityDefaultHigh,
verticalFittingPriority: UILayoutPriorityDefaultLow)
}
}
extension MyController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
if templateCommentCellForSizing == nil {
templateCommentCellForSizing = UserCommentCollectionViewCell(frame: CGRect(.zero)
}
return templateCommentCellForSizing!.sizeWith(width: availableWidth,
myString: myString)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment