Skip to content

Instantly share code, notes, and snippets.

@foxicode
Last active August 21, 2020 05:54
Show Gist options
  • Save foxicode/a542598cb2d4dbe81791a4b68bb094ee to your computer and use it in GitHub Desktop.
Save foxicode/a542598cb2d4dbe81791a4b68bb094ee to your computer and use it in GitHub Desktop.

Revisions

  1. foxicode revised this gist Aug 10, 2020. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions String+size.swift
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    import UIKit

    extension String {
    func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
    let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
  2. foxicode created this gist Aug 10, 2020.
    31 changes: 31 additions & 0 deletions String+size.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    extension String {
    func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
    let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
    let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)

    return ceil(boundingBox.height)
    }

    func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
    let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
    let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)

    return ceil(boundingBox.width)
    }
    }

    extension NSAttributedString {
    func height(withConstrainedWidth width: CGFloat) -> CGFloat {
    let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
    let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)

    return ceil(boundingBox.height)
    }

    func width(withConstrainedHeight height: CGFloat) -> CGFloat {
    let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
    let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)

    return ceil(boundingBox.width)
    }
    }