UITextView with hyperlink text

后端 未结 10 806
抹茶落季
抹茶落季 2020-11-27 19:23

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

Just click here to register

I can create a functi

10条回答
  •  粉色の甜心
    2020-11-27 20:16

    The same solution for Swift 3 using extensions :

    A. Add extension -

    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
        }
    }
    

    B. Add link url - let linkUrl = "https://www.my_website.com"

    C. Implement UITextViewDelegate in your ViewController like this -

     class MyViewController: UIViewController, UITextViewDelegate { 
     }
    

    D. Add delegate method to handle tap events -

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

    E. And finally, things to make sure for your UITextView under attribute inspector -

    1. Behaviour - Editable is turned OFF & Selectable is turned ON.
    2. Data Detectors - Link is turned ON.

    Usage -

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

    Cheers & happy coding!

提交回复
热议问题