带有超链接文本的UITextView [英] UITextView with hyperlink text

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

问题描述

使用不可编辑的UITextView,我想在iOS9 +中嵌入这样的文字:

With a non-editable UITextView, I would like to embed text like this in iOS9+:


只需点击这里注册

我可以创建一个函数操纵文本,但有更简单的方法吗?

I can create a function and manipulate the text but is there a simpler way?

我看到我可以使用NSTextCheckingTypeLink,因此在Interface Builder中可以直接获取没有click here部分的文本:

I see that I can use NSTextCheckingTypeLink so getting the text clickable without the 'click here' part is straightforward in Interface Builder:


只需 http://example.com 注册

我正在使用Xcode 8和Swift 3,如果这是相关的。

I'm using Xcode 8 and Swift 3 if that's relevant.

推荐答案

使视图控制器符合 UITextViewDelegate 和以下代码。您还需要设置 isEditable = false ,或者当用户点击文本视图时文本视图将进入文本编辑模式。

Make your view controller conform to UITextViewDelegate and a the following code. You also need to set isEditable = false or the text view will go into text-editing mode when user taps on it.

Swift 4:

override func viewDidLoad() {
    super.viewDidLoad()

    // You must set the formatting of the link manually
    let linkAttributes: [NSAttributedStringKey: Any] = [
        .link: NSURL(string: "https://www.apple.com")!,
        .foregroundColor: UIColor.blue
    ]

    let attributedString = NSMutableAttributedString(string: "Just click here to register")

    // Set the 'click here' substring to be the link
    attributedString.setAttributes(linkAttributes, range: NSMakeRange(5, 10))

    self.textView.delegate = self
    self.textView.attributedText = attributedString
    self.textView.isUserInteractionEnabled = true
    self.textView.isEditable = false
}

Swift 3及更早版本:

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


override func viewDidLoad() {
    super.viewDidLoad()

    // You must set the formatting of the link manually
    let linkAttributes = [
        NSLinkAttributeName: NSURL(string: "https://www.apple.com")!,
        NSForegroundColorAttributeName: UIColor.blue
    ] as [String : Any]

    let attributedString = NSMutableAttributedString(string: "Just click here to register")

    // Set the 'click here' substring to be the link
    attributedString.setAttributes(linkAttributes, range: NSMakeRange(5, 10))

    self.textView.delegate = self
    self.textView.attributedText = attributedString
    self.textView.isUserInteractionEnabled = true
    self.textView.isEditable = false
}

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆