UITextView with hyperlink text

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

    If you want to use multiple hyperlinks you can use this alternative for 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
      }
    }
    

    Usage:

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

提交回复
热议问题