Ezimetjan
9/18/2015 - 7:25 PM

String extension to find the layout size of a String with specified attributes.

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)
    }
}