Berry Blue
Berry Blue

Reputation: 16522

How do pass a string with an Image in SwiftUI

How do you pass a string that contains an Image in SwiftUI?

This works:

struct ContentView: View {
    var body: some View {
        Text("\(Image(systemName: "apple.logo")) Sign in with Apple")
            .padding()
    }
}

enter image description here

This does not work:

struct ContentView: View {
    var text = "\(Image(systemName: "apple.logo")) Sign in with Apple"
    var body: some View {
        Text(text)
            .padding()
    }
}

If I try to pass the string as a stored variable SwiftUI doesn't show the image.

enter image description here

Upvotes: 2

Views: 1134

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 52053

Use a Label instead of a Text component

Label("Sign in with Apple", systemImage: "apple.logo")

or if you want to use a string property then you must declare it as a LocalizedStringKey so that the right init will be called

var text:LocalizedStringKey = "\(Image(systemName: "apple.logo")) Sign in with Apple"

(without this it looks like what is used is the description property from CustomStringConvertible)

Have a look at this question and answer for some more in depth information about LocalizedStringKey

Upvotes: 4

Related Questions