Skip to content

Instantly share code, notes, and snippets.

@seanwolter
Created November 7, 2012 17:56
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 seanwolter/4033240 to your computer and use it in GitHub Desktop.
Save seanwolter/4033240 to your computer and use it in GitHub Desktop.
crappy loop to get the last word of each line in a UITextView
- (NSArray *)lastWordOfEachLine
{
NSMutableArray *wordArray = [@[] mutableCopy];
UITextPosition *firstRowStart = self.myTextView.beginningOfDocument;
UITextPosition *rowEnd = [self.myTextView.tokenizer positionFromPosition:firstRowStart
toBoundary:UITextGranularityLine
inDirection:UITextLayoutDirectionRight];
BOOL done = NO;
while (!done) {
UITextRange *range = [self.myTextView.tokenizer rangeEnclosingPosition:rowEnd
withGranularity:UITextGranularityWord
inDirection:UITextLayoutDirectionLeft];
NSString *lastWord = [self.myTextView textInRange:range];
int i = -1;
UITextPosition *newRowEnd = [self.myTextView positionFromPosition:rowEnd offset:i];
while (!lastWord) {
range = [self.myTextView.tokenizer rangeEnclosingPosition:newRowEnd
withGranularity:UITextGranularityWord
inDirection:UITextLayoutDirectionLeft];
i--;
lastWord = [self.myTextView textInRange:range];
newRowEnd = [self.myTextView positionFromPosition:rowEnd offset:i];
}
[wordArray addObject:lastWord];
done = [rowEnd isEqual:self.myTextView.endOfDocument];
rowEnd = [self.myTextView.tokenizer positionFromPosition:rowEnd
toBoundary:UITextGranularityLine
inDirection:UITextLayoutDirectionRight];
}
return [NSArray arrayWithArray:wordArray];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment