Skip to content

Instantly share code, notes, and snippets.

@barbuza
Last active June 24, 2017 03:49
Show Gist options
  • Save barbuza/5705301 to your computer and use it in GitHub Desktop.
Save barbuza/5705301 to your computer and use it in GitHub Desktop.
who said there is no links support in UILabel with attributed string?
#import <UIKit/UIKit.h>
@interface UILabel (TextTouch)
- (NSInteger)stringIndexUnder:(CGPoint)point;
@end
#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