Skip to content

Instantly share code, notes, and snippets.

@alexlavr
Last active October 24, 2016 10:02
Show Gist options
  • Save alexlavr/7064429 to your computer and use it in GitHub Desktop.
Save alexlavr/7064429 to your computer and use it in GitHub Desktop.
iOS7 TextKit
// Useful TextKit functions
// from Apple's Advanced Text Layouts and Effects with Text Kit
// https://developer.apple.com/wwdc/videos/
//Finding the last character
- (CGPoint) lastcharacter
{
NSLayoutManager *layoutManager = textView.layoutManager;
NSUInteger characterIndex = textView.textStorage.length - 1;
NSUInteger glyphIndex;
CGRect rect;
CGPoint glyphLocation;
glyphIndex = [layoutManager glyphIndexForCharacterIndex:characterIndex];
rect = [layoutManager lineFragmentRectForGlyphAtIndex:glyphIndex
effectiveRange:NULL];
glyphLocation = [layoutManager locationForGlyphAtIndex:glyphIndex];
glyphLocation.x += CGRectGetMinX(rect);
glyphLocation.y += CGRectGetMinY(rect);
return glyphLocation;
}
// Finding the word under a touch
- (void) getWordAt: (CGPoint) location
{
NSLayoutManager *layoutManager = textView.layoutManager;
CGPoint location = [touch locationInView:textView];
NSUInteger characterIndex;
characterIndex = [layoutManager characterIndexForPoint:location inTextContainer:textView.textContainer fractionOfDistanceBetweenInsertionPoints:NULL];
if (characterIndex < textView.textStorage.length)
{
// valid index
// Find the word range here
// using -enumerateSubstringsInRange:options:usingBlock:
}
}
//Counting the number of visual lines
- (NSUInteger) linesInText (UITextView *) textView
{
NSLayoutManager *layoutManager = textView.layoutManager;
NSTextContainer *textContainer = textView.textContainer;
NSRange glyphRange, lineRange = NSMakeRange(0, 0);
NSRect rect;
CGFloat lastOriginY = -1.0;
NSUInteger numberOfLines = 0;
glyphRange = [layoutManager glyphRangeForTextContainer:textContainer];
while (lineRange.location < NSMaxRange(glyphRange))
{
rect = [layoutManager lineFragmentRectForGlyphAtIndex:lineRange.location effectiveRange:&lineRange];
if (CGRectMinY(rect) > lastOriginY) ++numberOfLines;
lastOriginY = CGRectMinY(rect);
lineRange.location = NSMaxRange(lineRange);
}
return numberOfLines;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment