Last active
June 24, 2017 03:49
-
-
Save barbuza/5705301 to your computer and use it in GitHub Desktop.
who said there is no links support in UILabel with attributed string?
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
#import <UIKit/UIKit.h> | |
@interface UILabel (TextTouch) | |
- (NSInteger)stringIndexUnder:(CGPoint)point; | |
@end |
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
#import "UILabel+TextTouch.h" | |
#import <CoreText/CoreText.h> | |
@implementation UILabel (TextTouch) | |
- (NSInteger)stringIndexUnder:(CGPoint)point | |
{ | |
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(CFBridgingRetain((self.attributedText))); | |
CGPathRef path = CGPathCreateWithRect(self.bounds, nil); | |
CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, self.attributedText.length), path, nil); | |
NSArray *lines = CFBridgingRelease(CTFrameGetLines(frame)); | |
int count = lines.count; | |
for (int i = 0; i < count; i++) { | |
CTLineRef line = CFBridgingRetain([lines objectAtIndex:count - i - 1]); | |
CGRect bounds = CTLineGetBoundsWithOptions(line, kCTLineBoundsUseGlyphPathBounds); | |
CTFrameGetLineOrigins(frame, CFRangeMake(i, 1), &bounds.origin); | |
if (CGRectContainsPoint(bounds, point)) { | |
return CTLineGetStringIndexForPosition(line, point); | |
} | |
} | |
return NSNotFound; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment