带有超链接文本的 UITextView

UITextView with hyperlink text

对于不可编辑的 UITextView,我想在 iOS9+:

中嵌入这样的文本

Just click here to register

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

我发现我可以使用 NSTextCheckingTypeLink,因此在没有 'click here' 部分的情况下让文本可点击在 Interface Builder 中很简单:

Just http://example.com to register

如果相关,我使用 Xcode 8 和 Swift 3。

设置isEditable = false,否则文本视图将在用户点击时进入文本编辑模式。

Swift 4 岁及以后

let attributedString = NSMutableAttributedString(string: "Just click here to register")
let url = URL(string: "https://www.apple.com")!

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

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

// Set how links should appear: blue and underlined
self.textView.linkTextAttributes = [
    .foregroundColor: UIColor.blue,
    .underlineStyle: NSUnderlineStyle.single.rawValue
]

我想做同样的事情,结果只使用了一个 UIButton,标题 "click here" 被 UILabels "just " 和“注册”包围,然后:

@IBAction func btnJustClickHereLink(_ sender: UIButton) {
    if let url = URL(string: "http://example.com") {
        UIApplication.shared.openURL(url)
    }
}

Swift 3 使用扩展的相同解决方案:

一个。添加扩展名 -

extension UITextView {
    func hyperLink(originalText: String, hyperLink: String, urlString: String) {
        let style = NSMutableParagraphStyle()
        style.alignment = .center
        let attributedOriginalText = NSMutableAttributedString(string: originalText)
        let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
        let fullRange = NSMakeRange(0, attributedOriginalText.length)
        attributedOriginalText.addAttribute(NSLinkAttributeName, value: urlString, range: linkRange)
        attributedOriginalText.addAttribute(NSParagraphStyleAttributeName, value: style, range: fullRange)
        attributedOriginalText.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 10), range: fullRange)
        self.linkTextAttributes = [
            NSForegroundColorAttributeName: UIConfig.primaryColour,
            NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue,
        ]
        self.attributedText = attributedOriginalText
    }
}

乙。添加 link url - let linkUrl = "https://www.my_website.com"

摄氏度。像这样在 ViewController 中实现 UITextViewDelegate -

 class MyViewController: UIViewController, UITextViewDelegate { 
 }

D.添加委托方法来处理点击事件 -

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
    if (URL.absoluteString == linkUrl) {
        UIApplication.shared.openURL(URL)
    }
    return false
    }
}

E.最后,在属性检查器 -

下确保 UITextView 的事情
  1. 行为 - 可编辑已关闭,可选择已打开。
  2. 数据检测器 - Link 已打开。

用法 -

textView.hyperLink(originalText: "To find out more please visit our website", hyperLink: "website", urlString: linkUrl)

干杯,编码愉快!

Swift 4 使用扩展的相同解决方案:

extension UITextView {


    func hyperLink(originalText: String, hyperLink: String, urlString: String) {

            let style = NSMutableParagraphStyle()
            style.alignment = .left

            let attributedOriginalText = NSMutableAttributedString(string: originalText)
            let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
            let fullRange = NSMakeRange(0, attributedOriginalText.length)
            attributedOriginalText.addAttribute(NSAttributedStringKey.link, value: urlString, range: linkRange)
            attributedOriginalText.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: fullRange)
            attributedOriginalText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue, range: fullRange)
            attributedOriginalText.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 10), range: fullRange)

            self.linkTextAttributes = [
               kCTForegroundColorAttributeName: UIColor.blue,
               kCTUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue,
            ] as [String : Any]


            self.attributedText = attributedOriginalText
        }

}

您可以使用这种简单的方法将超链接添加到任何以 tag

开头的字符集
func addLink(forString string : NSMutableAttributedString
        ,baseURL : String
        ,tag : String){
        let array = string.string.replacingOccurrences(of: "\n", with: " ").components(separatedBy: " ")
        let filterArray = array.filter { (string) -> Bool in
            return string.contains(tag)
        }
        for element in filterArray {
            let removedHashtag = element.replacingOccurrences(of: tag, with: "")
            let url = baseURL + removedHashtag
            let range = NSString.init(string: (string.string)).range(of: element)
            string.addAttributes([NSAttributedStringKey.link : url.replacingOccurrences(of: " ", with: "")], range: range)
        }
    }

Swift 5 这是基于 Tejas 的回答,因为 类 中的一些项目已被弃用。

extension UITextView {


func hyperLink(originalText: String, hyperLink: String, urlString: String) {

    let style = NSMutableParagraphStyle()
    style.alignment = .left

    let attributedOriginalText = NSMutableAttributedString(string: originalText)
    let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
    let fullRange = NSMakeRange(0, attributedOriginalText.length)
    attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: urlString, range: linkRange)
    attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)
    attributedOriginalText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: fullRange)
    attributedOriginalText.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 10), range: fullRange)

    self.linkTextAttributes = [
        kCTForegroundColorAttributeName: UIColor.blue,
        kCTUnderlineStyleAttributeName: NSUnderlineStyle.single.rawValue,
        ] as [NSAttributedString.Key : Any]

    self.attributedText = attributedOriginalText
}

不要忘记将 UITextViewDelegate 添加到您的视图控制器并设置您的 let linkUrl = "https://example.com"

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
    if (URL.absoluteString == linkUrl) {
        UIApplication.shared.open(URL) { (Bool) in

        }
    }
    return false
}

用法保持不变:

textView.hyperLink(originalText: "To find out more please visit our website", hyperLink: "website", urlString: linkUrl)

Swift 4个代码. 可能是我是唯一一个需要设置多个链接并为一条消息中的单词着色的人。我创建了一个 AttribTextHolder class 来累积有关此容器内文本的所有信息,并轻松地在对象之间传递它以将文本设置到控制器深处某处的 UITextView。

class AttribTextHolder {

        enum AttrType {
            case link
            case color
        }

        let originalText: String
        var attributes: [(text: String, type: AttrType, value: Any)]


        init(text: String, attrs: [(text: String, type: AttrType, value: Any)] = [])
        {
            originalText = text
            attributes = attrs
        }

        func addAttr(_ attr: (text: String, type: AttrType, value: Any)) -> AttribTextHolder {
            attributes.append(attr)
            return self
        }

        func setTo(textView: UITextView)
        {
            let style = NSMutableParagraphStyle()
            style.alignment = .left

            let attributedOriginalText = NSMutableAttributedString(string: originalText)

            for item in attributes {
                let arange = attributedOriginalText.mutableString.range(of: item.text)
                switch item.type {
                case .link:
                    attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: item.value, range: arange)
                case .color:
                    var color = UIColor.black
                    if let c = item.value as? UIColor { color = c }
                    else if let s = item.value as? String { color = s.color() }
                    attributedOriginalText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: arange)
                default:
                    break
                }
            }

            let fullRange = NSMakeRange(0, attributedOriginalText.length)
            attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)

            textView.linkTextAttributes = [
                kCTForegroundColorAttributeName: UIColor.blue,
                kCTUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue,
            ] as [String : Any]

            textView.attributedText = attributedOriginalText
        }
 }

这样使用:

 let txt = AttribTextHolder(text: "To find out more visit our website or email us your questions")
            .addAttr((text: "our website", type: .link, "http://example.com"))
            .addAttr((text: "our website", type: .color, "#33BB22"))
            .addAttr((text: "email us", type: .link, "mailto:us@example.com"))
            .addAttr((text: "email us", type: .color, UIColor.red))
 ....
 ....
 txt.setTo(textView: myUITextView)

同样在这段代码中,我使用简单的字符串扩展将字符串十六进制值转换为 UIColor 对象

extension String {
/// Converts string color (ex: #23FF33) into UIColor
func color() -> UIColor {
    let hex = self.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
    var int = UInt32()
    Scanner(string: hex).scanHexInt32(&int)
    let a, r, g, b: UInt32
    switch hex.characters.count {
    case 3: // RGB (12-bit)
        (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
    case 6: // RGB (24-bit)
        (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
    case 8: // ARGB (32-bit)
        (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
    default:
        (a, r, g, b) = (255, 0, 0, 0)
    }
    return UIColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
  }
}

使用 Swift >= 4:

let descriptionText = NSMutableAttributedString(string:"To learn more, check out our ", attributes: [:])

let linkText = NSMutableAttributedString(string: "Privacy Policy and Terms of Use", attributes: [NSAttributedString.Key.link: URL(string: example.com)!])

descriptionText.append(linkText)

如果您想使用多个超链接,您可以使用此替代方法 Swift 5

extension UITextView {

  func addHyperLinksToText(originalText: String, hyperLinks: [String: String]) {
    let style = NSMutableParagraphStyle()
    style.alignment = .left
    let attributedOriginalText = NSMutableAttributedString(string: originalText)
    for (hyperLink, urlString) in hyperLinks {
        let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
        let fullRange = NSRange(location: 0, length: attributedOriginalText.length)
        attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: urlString, range: linkRange)
        attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)
        attributedOriginalText.addAttribute(NSAttributedString.Key.font, value: YourFont, range: fullRange)
    }
    
    self.linkTextAttributes = [
        NSAttributedString.Key.foregroundColor: YourColor,
        NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
    ]
    self.attributedText = attributedOriginalText
  }
}

用法:

yourTextView.addHyperLinksToText(originalText: "Testing hyperlinks here and there", hyperLinks: ["here": "someUrl1", "there": "someUrl2"])

通过 UITextView 实现超链接的更安全方案

var termsConditionsTextView: UITextView = {
let view = UITextView()
 view.backgroundColor = .clear
 view.textAlignment = .left
 
 let firstTitleString = "By registering for THIS_APP I agree with the "
 let secondTitleString = "Terms & Conditions"
 let finishTitleString = firstTitleString + secondTitleString
 let attributedString = NSMutableAttributedString(string: finishTitleString)
 attributedString.addAttribute(.link, value: "https://whosebug.com", range: NSRange(location: firstTitleString.count, length: secondTitleString.count))
 
 view.attributedText = attributedString
 view.textContainerInset = .zero
 view.linkTextAttributes = [
     .foregroundColor: UIColor.blue,
     .underlineStyle: NSUnderlineStyle.single.isEmpty
 ]
 
 view.font = view.font = UIFont(name: "YOUR_FONT_NAME", size: 16)
 view.textColor = UIColor.black
 
 return view }()

SWIFT 5 个以上 LINK

import UIKit

public extension UITextView {
    
    func hyperLink(originalText: String, linkTextsAndTypes: [String: String]) {
        
        let style = NSMutableParagraphStyle()
        style.alignment = .left
        
        let attributedOriginalText = NSMutableAttributedString(string: originalText)
        
        for linkTextAndType in linkTextsAndTypes {
            let linkRange = attributedOriginalText.mutableString.range(of: linkTextAndType.key)
            let fullRange = NSRange(location: 0, length: attributedOriginalText.length)
            attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: linkTextAndType.value, range: linkRange)
            attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)
            attributedOriginalText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: fullRange)
            attributedOriginalText.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 10), range: fullRange)
        }
        
        self.linkTextAttributes = [
            kCTForegroundColorAttributeName: UIColor.blue,
            kCTUnderlineStyleAttributeName: NSUnderlineStyle.single.rawValue
        ] as [NSAttributedString.Key: Any]
        
        self.attributedText = attributedOriginalText
    }
}

以及您的 viewController 中的用法:

@IBOutlet weak var termsHyperlinkTextView: UITextView! {
        didSet {
            termsHyperlinkTextView.delegate = self
            termsHyperlinkTextView.hyperLink(originalText: "Check out terms & conditions or our privacy policy",
                                             linkTextsAndTypes: ["terms & conditions": LinkType.termsAndConditions.rawValue,
                                                                 "privacy policy": LinkType.privacyPolicy.rawValue])

        }
    }
enum LinkType: String {
        case termsAndConditions
        case privacyPolicy
    }
// MARK: - UITextViewDelegate
extension ViewController: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        if let linkType = LinkType(rawValue: URL.absoluteString) {
            // TODO: handle linktype here with switch or similar.
        }
        return false
    }
}