Created
January 30, 2023 10:32
-
-
Save karambirov/8913e7e08fb36e020fad45f5ebe46b52 to your computer and use it in GitHub Desktop.
Extensions for calculation size of a Swift String
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
import Foundation | |
public extension String { | |
func calculateSize(attributes: [NSAttributedString.Key: Any], constrainedSize: CGSize) -> CGSize { | |
let rect = (self as NSString).boundingRect( | |
with: constrainedSize, | |
options: [.usesLineFragmentOrigin, .usesFontLeading], | |
attributes: attributes, | |
context: nil | |
) | |
return CGSize(width: ceil(rect.width), height: ceil(rect.height)) | |
} | |
func calculateSize(font: UIFont, constrainedSize: CGSize) -> CGSize { | |
calculateSize(attributes: [NSAttributedString.Key.font: font], constrainedSize: constrainedSize) | |
} | |
func calculateHeight(font: UIFont, constrainedWidth: CGFloat) -> CGFloat { | |
calculateSize( | |
font: font, | |
constrainedSize: CGSize(width: constrainedWidth, height: CGFloat.greatestFiniteMagnitude) | |
).height | |
} | |
func calculateWidth(font: UIFont, constrainedHeight: CGFloat) -> CGFloat { | |
calculateSize( | |
font: font, | |
constrainedSize: CGSize(width: CGFloat.greatestFiniteMagnitude, height: constrainedHeight) | |
).width | |
} | |
} | |
public extension NSAttributedString { | |
func calculateSize(constrainedSize: CGSize) -> CGSize { | |
let rect = boundingRect( | |
with: constrainedSize, | |
options: [.usesLineFragmentOrigin, .usesFontLeading], | |
context: nil | |
) | |
return CGSize(width: ceil(rect.width), height: ceil(rect.height)) | |
} | |
func calculateHeight(constrainedWidth: CGFloat) -> CGFloat { | |
calculateSize( | |
constrainedSize: CGSize(width: constrainedWidth, height: CGFloat.greatestFiniteMagnitude) | |
).height | |
} | |
func calculateWidth(constrainedHeight: CGFloat) -> CGFloat { | |
calculateSize( | |
constrainedSize: CGSize(width: CGFloat.greatestFiniteMagnitude, height: constrainedHeight) | |
).width | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment