Created
September 15, 2015 13:34
-
-
Save plumhead/945e0f2945a3ffea378a to your computer and use it in GitHub Desktop.
String extension to find the layout size of a String with specified attributes.
This file contains 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
extension String { | |
func size(withAttributes attrs: [String:AnyObject], constrainedTo box: NSSize) -> NSRect { | |
let storage = NSTextStorage(string: self) | |
let container = NSTextContainer(containerSize: NSSize(width: box.width, height: box.height)) | |
let layout = NSLayoutManager() | |
layout.addTextContainer(container) | |
storage.addLayoutManager(layout) | |
storage.addAttributes(attrs, range: NSMakeRange(0, storage.length)) | |
container.lineFragmentPadding = 0.0 | |
let _ = layout.glyphRangeForTextContainer(container) | |
return layout.usedRectForTextContainer(container) | |
} | |
} |
Obviously you could extend to pass a function in to configure the text container rather than simply setting a default lineFragmentPaddding as the example shows.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use as follows