Hyperlinks in a UITextView

后端 未结 5 1154
無奈伤痛
無奈伤痛 2020-12-01 16:18

I am trying to create a UITextView with a hyperlink so that when the user clicks on the link, they are taken to safari to open the we

5条回答
  •  执笔经年
    2020-12-01 16:59

    Use NSAttributedString

    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Google" 
                                                                           attributes:@{ NSLinkAttributeName: [NSURL URLWithString:@"http://www.google.com"] }];
    self.textView.attributedText = attributedString;
    

    Sure, you can set just a portion of the text to be the link. Please read more about the NSAttributedString here.

    If you want to have more control and do something before opening the link. You can set the delegate to the UITextView.

    - (void)viewDidLoad {
        ...
        self.textView.delegate = self; // self must conform to UITextViewDelegate protocol
    }
    
    ...
    
    - (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
        // Do whatever you want here
        NSLog(@"%@", URL); // URL is an instance of NSURL of the tapped link
        return YES; // Return NO if you don't want iOS to open the link
    }
    

提交回复
热议问题