Skip to content

Instantly share code, notes, and snippets.

@thornpig
Created February 9, 2016 18:12
Show Gist options
  • Save thornpig/21bff0fbb078e3a8e5ca to your computer and use it in GitHub Desktop.
Save thornpig/21bff0fbb078e3a8e5ca to your computer and use it in GitHub Desktop.
Find index of tapped character in UILabel
-(NSInteger)indexOfTappedCharacterWithTapGesture:(UITapGestureRecognizer *)tapGesture
{
CGPoint location = [tapGesture locationInView:self];
// init text storage
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString: self.attributedText];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[textStorage addLayoutManager:layoutManager];
// init text container
// NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(self.frame.size.width, self.frame.size.height+100) ];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(self.frame.size.width, self.frame.size.height) ];
textContainer.lineFragmentPadding = 0;
textContainer.maximumNumberOfLines = self.numberOfLines;
textContainer.lineBreakMode = self.lineBreakMode;
[layoutManager addTextContainer:textContainer];
NSInteger characterIndex = [layoutManager characterIndexForPoint: location
inTextContainer:textContainer
fractionOfDistanceBetweenInsertionPoints:NULL];
return characterIndex;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment