UITextView with hyperlink text

后端 未结 10 855
抹茶落季
抹茶落季 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:10

    Swift 5 This is based on Tejas' answer as a few items in both classes were deprecated.

    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
    }
    

    Don't forget to add UITextViewDelegate to your view controller and set your 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
    }
    

    Usage stays the same:

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

提交回复
热议问题