When using SwiftUI with iOS 14, I was unable to find out how to render html markup into actual text. I used SwiftSoup to parse the HTML into a string, but it removed <br/>
and it didn't parse it into an NSAttributedString for formatting. Once I inserted my own line break via \n
in the attributed string, UIKit removed the formatting for all links after the first line break. Overall, multiple pieces of breaking library code that make for one convoluted mess.
Asked
Active
Viewed 381 times
-1

Eli017
- 31
- 7
1 Answers
0
I learned that the best thing to do to keep the link formatting of a TextView
in SwiftUI is done through several steps.
- Create a
UIViewRepresentable
forTextView
(code down below). - Substitute any HTML
<br />
with custom string so that it doesn't get erased by SwiftSoup (can't be\n
). - Break the new HTML string by using that new custom string as the delimiter.
- Loop through the new string array and declare a new
DataTextView
.
Implementation:
let docTextArray = info.components(separatedBy: "customNewLinee")
ForEach(docTextArray, id: \.self) { infoLine in
DataTextView(text: NSAttributedString(string: infoLine), dataDetectorTypes: [.all])
}
UIBridge:
import SwiftUI
struct DataTextView: UIViewRepresentable {
var text: NSAttributedString
var dataDetectorTypes: UIDataDetectorTypes
var fontName: String = "Roboto-Bold"
var fontSize: CGFloat = 16
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.attributedText = text
textView.autocapitalizationType = .sentences
textView.isEditable = false
textView.isScrollEnabled = false
textView.textColor = UIColor(.IMGGray)
textView.font = UIFont(name: fontName, size: fontSize)
textView.dataDetectorTypes = dataDetectorTypes
textView.linkTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.systemBlue,
NSAttributedString.Key.font: UIFont(name: "Roboto", size: 16)!
]
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
}
}

Eli017
- 31
- 7