Created
February 9, 2016 18:12
-
-
Save thornpig/21bff0fbb078e3a8e5ca to your computer and use it in GitHub Desktop.
Find index of tapped character in UILabel
This file contains hidden or 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
-(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