Created
October 19, 2017 14:53
-
-
Save dirtyhenry/1820b9cb07095c42f427e38a912477d4 to your computer and use it in GitHub Desktop.
Definitive UICollectionViewCell dynamic size
This file contains 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
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) | |
} | |
} |
This file contains 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
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