String+heightForConstrainedWidth.swift 1001 B

12345678910111213141516171819202122232425
  1. //
  2. // String+heightForConstrainedWidth.swift
  3. // NotificationBanner
  4. //
  5. // Created by Sascha Gordner on 03.10.18.
  6. // Copyright © 2018 Dalton Hinterscher. All rights reserved.
  7. //
  8. // https://stackoverflow.com/questions/30450434/figure-out-size-of-uilabel-based-on-string-in-swift
  9. import UIKit
  10. public extension String {
  11. /// Calculates the height a label will need in order to display the String for the given width and font.
  12. ///
  13. /// - Parameters:
  14. /// - width: Max width of the bounding rect
  15. /// - font: Font used to render the string
  16. /// - Returns: Height a string will need to be completely visible
  17. func height(forConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
  18. let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
  19. let boundingBox = self.boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font: font], context: nil)
  20. return boundingBox.height
  21. }
  22. }