本文介绍了UITextView中的超链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个带有超链接的UITextView,这样当用户点击链接时,他们就会被带到safari来打开网页。我已阅读文本视图的链接检测器,但如果文本中存在实际网址(即www.google.com),这些示例始终显示链接检测有效。我希望它是常规文本,单击时会打开关联的URL。 (即Google就是文字,点击后会打开一个网址www.google.com)。如何在iOS7 / 8中完成此操作?

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 webpage. I have read on link detectors for a textview but those samples always show link detection working if an actual url is present in the text (ie. www.google.com). I want it to be regular text that, when clicked, opens an associated URL. (ie. Google is the text and when clicked, opens up a url www.google.com). How can I accomplish this in iOS7/8?

推荐答案

使用 NSAttributedString

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

当然,您只需将文本的一部分设置为链接即可。请详细了解 NSAttributedString

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

如果你想在打开链接之前有更多控制权并做一些事情。您可以将委托设置为 UITextView

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
}

这篇关于UITextView中的超链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 18:24