Skip to content

Instantly share code, notes, and snippets.

@fethica
Last active February 19, 2018 18:01
Show Gist options
  • Save fethica/1b54a6f137f891cf036409ac49ecf255 to your computer and use it in GitHub Desktop.
Save fethica/1b54a6f137f891cf036409ac49ecf255 to your computer and use it in GitHub Desktop.
Estimated height for a cell based on string value and font type
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