Search code examples
iosuitextviewnsattributedstring

iOS7 UITextView set NSLinkAttributeName attribute but can not click


enter image description here

@interface ViewController ()<UITextViewDelegate>


- (void)viewDidLoad
{
    [super viewDidLoad];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"www.google.com"];
    NSDictionary *linkDic = @{ NSLinkAttributeName : [NSURL URLWithString:@"http://www.google.com"] };
    [str setAttributes:linkDic range:[[str string] rangeOfString:@"www.google.com"]];
    _textView.attributedText = str;
}


- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    NSLog(@"=============%@",URL);
    return YES;
}

Is there something wrong?


Solution

  • Set the following in IB > Utilities > Attributes Inspector. Notably the UITextView cannot be editable and have links enabled.

    UITextView Settings

    You can also do the same with code:

    _textView.editable = NO;
    _textView.dataDetectorTypes = UIDataDetectorTypeLink;