Skip to content

Instantly share code, notes, and snippets.

@zhjuncai
Forked from plumhead/StringSize.swift
Last active September 20, 2015 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhjuncai/6af27ca9649126dd326c to your computer and use it in GitHub Desktop.
Save zhjuncai/6af27ca9649126dd326c to your computer and use it in GitHub Desktop.
String extension to find the layout size of a String with specified attributes.
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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment