Created
August 10, 2014 17:06
-
-
Save yoshimin/858d14751fc1c00807d2 to your computer and use it in GitHub Desktop.
NSAttributedStringを使ってリンク文字を作る
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
#import "YMNViewController.h" | |
NSString *const Text = @"The iOS Developer Program provides a complete and integrated process for developing and distributing iOS apps on the App Store. Learn more"; | |
NSString *const LinkText = @"Learn more"; | |
@interface YMNViewController () | |
@property (nonatomic, strong) UITextView *textView; | |
@property (nonatomic, strong) UITapGestureRecognizer *tapGesture; | |
@end | |
@implementation YMNViewController | |
- (void)viewDidLoad | |
{ | |
[super viewDidLoad]; | |
self.textView = [[UITextView alloc] initWithFrame:CGRectMake(0.f, 20.f, self.view.frame.size.width, self.view.frame.size.height)]; | |
self.textView.userInteractionEnabled = YES; | |
self.textView.editable = NO; | |
// AttributedStringでリンクっぽく装飾する | |
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:Text]; | |
NSRange link = [Text rangeOfString:LinkText]; | |
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:link]; | |
[attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:link]; | |
self.textView.attributedText = attributedString; | |
// UITapGestureRecognizerをセットしてタップされた文字の位置を取得できるようにする | |
self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapText:)]; | |
[self.textView addGestureRecognizer:self.tapGesture]; | |
[self.view addSubview:self.textView]; | |
} | |
- (void)tapText:(UITapGestureRecognizer*)tap { | |
// タップされた座標をもとに最寄りの文字列の位置を取得 | |
CGPoint location = [tap locationInView:self.textView]; | |
UITextPosition *textPosition = [self.textView closestPositionToPoint:location]; | |
// テキストの先頭とタップした文字の距離をNSIntegerで取得 | |
NSInteger selectedPosition = [self.textView offsetFromPosition:_textView.beginningOfDocument toPosition:textPosition]; | |
NSRange linkRange = [Text rangeOfString:LinkText]; | |
// タップした文字がリンク文字のrangeに含まれるか判定 | |
if (NSLocationInRange (selectedPosition,linkRange)) { | |
NSLog(@"Learn more"); | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment