你要放入UITextView的文字

契約編號00261034115<br><a href=https://docs.google.com/gview?202003/00261034115-contract.pdf'>合約連結</a><br>親愛的會員您好。

特殊html href 手動轉換成UITextView連結

func findHtmlHref (textView : UITextView ,content : String) -> UITextView{
    if matches(for: "href", in: content).count == 0 {
        let newContent = content.replacingOccurrences(of:"<br>", with: "\n")
        textView.text = newContent
        return textView
    }

    do {
        let html = content
        let doc: Document = try SwiftSoup.parse(html)
        let link: Element = try doc.select("a").first()!
        let linkHref: String = try link.attr("href");
        let linkText: String = try link.text();
        if linkHref == "" {
            return textView
        }
        var newContent = content.replacingOccurrences(of:"<a href=\'" + linkHref + "\'>合約連結</a>", with: "@Terms@")
        newContent = newContent.replacingOccurrences(of:"<br>", with: "\n")

        textView.text = newContent
        textView.attributedText = textView.attributedText?
            .replace(placeholder: "@Terms@", with: linkText, url: linkHref)

        return textView
    } catch Exception.Error(let type, let message) {
        print(message)
        return textView
    } catch {
        print("error")
        return textView
    }
}

呼叫func

contentTextView = findHtmlHref(textView : 你得textView , content: 你的文字)

結果

UITextView 直接塞 html格式

extension String {
var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return nil }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return nil
        }
    }

    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}

呼叫

contentTextView.attributedText = 你得文字.htmlToAttributedString

結果

Swift更多文章

Swift 彈出視窗 AlertController 的使用方法 💥

Swift 判斷螢幕方向 📱

Swift Core Data 實現 💾🔥

Swift UISegmentedControl 💻分段控制器!

Swift 實現抽屜效果 🧹

Categorized in: