Home > Enterprise >  @Published Attributed Strings Not Working
@Published Attributed Strings Not Working

Time:01-11

Attributed Strings don't seem to retain their attributes when created in the ViewModel and passed to a SwiftUI View. Is there a way to make @Published strings with bold/italics/etc in a ViewModel that retain their attributes in the View?

The following correctly applies bold styling

struct ContentView: View {
   var body: some View {
       Text( "**This** should be bold")
   }
}

However, when using a ViewModel it produces: **This** should be bold

final class ViewModel: ObservableObject {
    @Published var attributedString = "**This** should be bold"
}

struct ContentView: View {
   @ObservedObject private var viewModel = ViewModel()

   var body: some View {
       Text(viewModel.attributedString)
   }
}

I've also tried setting the type as AttributedString, however that doesn't seem to make a difference.

CodePudding user response:

You can use AttributedString(markdown: ) but as it throws, you have to use it e.g.in the init.

final class ViewModel: ObservableObject {
    @Published var attributedString: AttributedString
    
    init() {
        self.attributedString = ""
        try? attributedString = AttributedString(markdown: "**This** should be bold")
    }
}
  • Related