Last active
February 19, 2018 18:01
-
-
Save fethica/1b54a6f137f891cf036409ac49ecf255 to your computer and use it in GitHub Desktop.
Estimated height for a cell based on string value and font type
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
func estimateHeight(string: String?, font: UIFont, right: CGFloat = 0, left: CGFloat = 0) -> CGFloat { | |
guard let string = string else { return 0 } | |
let width = view.frame.width - right - left | |
let rect = NSString(string: string).boundingRect(with: CGSize(width: width, height: 1000.0), options: NSStringDrawingOptions.usesFontLeading.union(NSStringDrawingOptions.usesLineFragmentOrigin), attributes: [NSAttributedStringKey.font: font], context: nil) | |
return rect.height | |
} | |
// Usage for UICollectionViewCell | |
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { | |
let margin = 16 | |
let cellHeight = estimateHeight(string: "Long string here!", font: UIFont(name: UIFont.preferredFont(forTextStyle: .body), right: margin, left: margin) | |
return CGSize(width: view.frame.width, height: margin + cellHeight + margin) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment