buguibu / ios-notes-issues-lessons

Notes, issues and lessons about my iOS development experience
2 stars 0 forks source link

HTML anchor links on UITextView #2

Open buguibu opened 5 years ago

buguibu commented 5 years ago

You can add dynamically HTML content to a UILabel in this way:

        var attributedString: NSMutableAttributedString?
        let styledHtmlText = String(
            format: format,
            string
        )
        if let data = styledHtmlText.data(using: String.Encoding.unicode),
            let attributedText = try? NSMutableAttributedString(
                data: data,
                options: [.documentType: NSAttributedString.DocumentType.html],
                documentAttributes: nil
            ) {
            attributedString = attributedText
        }
        return attributedString
    }

where format param could be a string like: <div><style type="text/css"> a{ color: #C63663 !important; text-decoration: none; }%@</div>

and you will get a UILAbel that accepts HTML content with style but it doesn't allows you to open that anchor links on a web browser.

So for enable anchor links you must use a UITextView with user interaction enabled and link data detectors enabled. you can style the HTML content as in UILable but for coloring anchors you must make use of: textView.linkTextAttributes = [ .foregroundColor: UIColor.red ] and for enable interactivity: textView.delegate = self

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