ios UITextView 中的超链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26962530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:39:10  来源:igfitidea点击:

Hyperlinks in a UITextView

iosobjective-cios8uitextview

提问by John Baum

I am trying to create a UITextViewwith a hyperlinkso that when the user clicks on the link, they are taken to safarito open the webpage. I have read on link detectors for a textviewbut 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?

我正在尝试创建一个UITextViewhyperlink以便当用户点击链接时,他们会被带到safari打开网页。我已经阅读了有关链接检测器的文章,textview但如果文本中存在实际 url(即www.google.com),这些示例总是显示链接检测有效。我希望它是常规文本,单击时会打开关联的 URL。(即 Google 是文本,点击后会打开一个网址www.google.com)。我怎样才能在 iOS7/8 中做到这一点?

回答by yusuke024

Use NSAttributedString

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 NSAttributedStringhere.

当然,您可以将文本的一部分设置为链接。请阅读有关NSAttributedString此处的更多信息。

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

如果你想在打开链接之前有更多的控制权并做一些事情。您可以将委托设置为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
}

回答by Amr Angry

Swift 3, iOS10 , Xcode 9

斯威夫特 3、iOS10、Xcode 9

@sikhapol's answer is really nice if you knew exactly the words you want to parse like "word dictionary" some how

@sikhapol 的回答非常好,如果你确切地知道你想像“单词词典”那样解析的单词的话

it's all about the string it self that displayed in UITextView

这都是关于它自己在 UITextView 中显示的字符串

My solution is based the text renderingif you make the UITextView render an html tags you may use href tag

我的解决方案是基于文本呈现,如果你让 UITextView 呈现一个你可以使用 href 标签的 html 标签

Here is some Code references you may use

这是您可能会使用的一些代码参考

first you need to configure UITextView from interface builder or form code to

首先你需要从界面构建器或表单代码配置 UITextView 到

  1. Selectable
  2. Data detectores
  1. 可选择
  2. 数据检测器

Note : do not make the textview editable

注意:不要使文本视图可编辑

Interface builder

界面生成器

enter image description here

在此处输入图片说明

programmatically

以编程方式

         let htmlData = NSString(string: "go to <a href=\"http://www.google.com\">google</a> and search for it").data(using: String.Encoding.unicode.rawValue)


        let attributedString = try! NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
        yourUIViewView.isSelectable = true
        yourUIViewView.dataDetectorTypes = .link
        yourUIViewView.attributedText = attributedString
        yourUIViewView.delegate = self

for the UITextViewDelegate

对于 UITextViewDelegate

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {

       // check for the url string for performing your own custom actions here
      let urlString = URL.absoluteString

       // Return NO if you don't want iOS to open the link
        return true
     }

回答by splangi

A nifty little extension that I wrote and use (Swift 4.2, tested on iOS 12.1)

我编写和使用的一个漂亮的小扩展(Swift 4.2,在 iOS 12.1 上测试)

extension NSAttributedString {
    func replace(placeholder: String, with hyperlink: String, url: String) -> NSAttributedString {
        let mutableAttr = NSMutableAttributedString(attributedString: self)

        let hyperlinkAttr = NSAttributedString(string: hyperlink, attributes: [NSAttributedString.Key.link: URL(string: url)!])

        let placeholderRange = (self.string as NSString).range(of: placeholder)

        mutableAttr.replaceCharacters(in: placeholderRange, with: hyperlinkAttr)
        return mutableAttr
    }
}

Usage:

用法:

//Set through code or through interface builder
footerText.isSelectable = true
footerText.dataDetectorTypes = .link

//Keeps the original formatting from xib or storyboard
footerText.text = "By continuing, you are indicating that you accept our @Terms@ and @Privacy@."
footerText.attributedText = footerText.attributedText?
        .replace(placeholder: "@Terms@", with: "Terms and Conditions", url: AppUrl.terms)
        .replace(placeholder: "@Privacy@", with: "Privacy Policy", url: AppUrl.privacy)

回答by Tiago Mendes

This code sample has two different links in the same label and URL color is set to avoid the default blue.

此代码示例在同一标签中有两个不同的链接,并且 URL 颜色设置为避免默认蓝色。

UITextView * textTerm = [UITextView new];
NSMutableAttributedString *attrRight = [[NSMutableAttributedString alloc] initWithString:@"Terms of Service"
                                                                       attributes:@{ NSLinkAttributeName: [NSURL URLWithString:@"http://www.google.com"] }];
NSMutableAttributedString *attrLeft = [[NSMutableAttributedString alloc] initWithString:@"Privacy Policy"
                                                                       attributes:@{ NSLinkAttributeName: [NSURL URLWithString:@"http://www.google.com"] }];
[attrRight appendAttributedString:attrLeft];
textTerm.attributedText = attrRight;
textTerm.editable = NO;
textTerm.dataDetectorTypes = UIDataDetectorTypeAll;
textTerm.linkTextAttributes = [UIColor whiteColor];
textTerm.backgroundColor = [UIColor clearColor];

回答by Marek Manduch

if you want active substring in your UITextView then you can use my extended TextView... its short and simple. You can edit it as you want.

如果你想在你的 UITextView 中使用活动子字符串,那么你可以使用我的扩展 TextView ......它简短而简单。您可以根据需要对其进行编辑。

how to use (range = substring location):

如何使用(范围=子串位置):

[self.textView addTapActionWithRange:range withActionBlock:^{
      // anything you want to do - show something
}];

result: enter image description here

结果: 在此处输入图片说明

source code: https://github.com/marekmand/ActiveSubstringTextView

源代码:https: //github.com/marekmand/ActiveSubstringTextView