Swiftui: passing interpolated string with Image into Text view as String doesn't show Image given

Viewed 428

when i pass an interpolated string with Image into a Text view, it returns incorrectly.


import SwiftUI

struct UserMediaCell: View {
    var body: some View {
        subView(label:"\(Image(systemName: "ellipsis"))") 
        // shows incorrectly:
        // Image(provider: SwiftUI.ImageProviderBox<SwiftUI.Image.(unknown context at $18c350410).NamedImageProvider>)

        Text("\(Image(systemName: "ellipsis"))") 
        // shows correctly. (sf symbol visible)
    }
}

struct subView: View {
    @State var label: String

    var body: some View {
        Text(label)
    }
}

how do i solve this?

1 Answers

This is because your subview is taking the result of the string interpolation as a String type. Where the Text view that is working correctly is not using a String to initialize the view, but a Localized String Key.

Change your subview to account for that like so:

// Structs, Classes, and Actors should start with a Capital Letter BTW
struct SubView: View {
    @State var label: LocalizedStringKey

    var body: some View {
        Text(label)
    }
}
Related