Created
November 13, 2015 16:38
-
-
Save plumhead/a9350b7b19da731b188f to your computer and use it in GitHub Desktop.
Useful NSTextView extensions
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 NSTextView { | |
func rectForRange(range: NSRange) -> NSRect? { | |
guard let layout = self.layoutManager, container = self.textContainer else {return nil} | |
let rng = layout.glyphRangeForCharacterRange(range, actualCharacterRange: nil) | |
let rct = layout.boundingRectForGlyphRange(rng, inTextContainer: container) | |
return NSOffsetRect(rct, self.textContainerOrigin.x, self.textContainerOrigin.y) | |
} | |
func rectForSelectedRange() -> NSRect? { | |
return rectForRange(self.selectedRange()) | |
} | |
func scrollAndHighlight(toLine ln: Int) { | |
scroll(toLine: ln) { (range) -> () in | |
self.setSelectedRange(range) | |
} | |
} | |
func scroll(toLine ln: Int, withAction f: (range:NSRange) -> ()) { | |
guard let layout = self.layoutManager else {return} | |
guard ln >= 1 else {return} | |
let numGlyphs = layout.numberOfGlyphs | |
var i = 0 | |
var cl = 1 | |
var targetRange = NSRange() | |
while i < numGlyphs { | |
let _ = layout.lineFragmentRectForGlyphAtIndex(i, effectiveRange: &targetRange) | |
if cl == ln { | |
self.scrollRangeToVisible(targetRange) | |
return f(range: targetRange) | |
} | |
i += targetRange.length | |
cl++ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment