In my project, I am getting some text from backend which could have html tags. For this, I am converting the string to attributed string. However I noticed that when the string has html tags with color in it and when the text is displayed in toolbar, then the text displays with an ellipsis towards the end. Sharing code below:
import SwiftUI
struct ContentViewA: View {
@State private var displayText: AttributedString?
var body: some View {
NavigationStack {
VStack {
Text(displayText ?? "")
}
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button {
} label: {
Text("Done").font(.body.bold())
}
}
ToolbarItem(placement: .principal) {
Text(displayText ?? "")
}
}
.onAppear {
let string = "<div><p><span style=\"color:#FF0000;\">Hello World</span></p></div>"
displayText = string.convertToAttributedString
/// Note: If I don't set the font, then the ellipsis are not displayed in the toolbar, but I need this font style.
displayText?.font = .body.bold()
}
}
}
}
extension String {
var convertToAttributedString: AttributedString? {
guard let data = data(using: .utf8) else { return nil }
var attributedString: AttributedString?
if let nsAttributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil) {
attributedString = try? AttributedString(nsAttributedString, including: \.uiKit)
}
return attributedString
}
}
I am printing displayText in the body of the view and am not seeing ellipsis at the end of the string, but in toolbar, I am seeing ellipsis. I am unable to figure out what's causing this and what can be the fix for it. However, if I avoid setting the font on attributed string, then the ellipsis are not displayed in toolbar. However, I need to set the string to a specific font style.
How can I avoid ellipsis in toolbar and while also setting the required font on the string?
I can't reproduce the ellipsis running with iOS 18.3.1 on an iPhone 16, but I was able to see that a CR is being added to the end of the string. This is most likely because of the <p> or the <div> tags.
note:
let string = "<div><p><span style=\"color:#FF0000;\">Hello World</span></p></div>"
displayText = string.convertToAttributedString
print("the text = '\(NSAttributedString(displayText!).string)'")
prints:
the text = 'Hello World
'
but
let string = "<span style=\"color:#FF0000;\">Hello World</span>"
displayText = string.convertToAttributedString
print("the text = '\(NSAttributedString(displayText!).string)'")
prints:
the text = 'Hello World'