0

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

Berry Blue
  • 15,330
  • 18
  • 62
  • 113
  • You could use a `(NS)AttributedString` – Larme Feb 07 '23 at 16:51
  • 1
    *string that contains an Image* is a contradiction in terms. `String` and `Image` are not related to each other (the Unicode Emojis are a special case). Use `Label` as suggested by Joakim. – vadian Feb 07 '23 at 17:26
  • I updated my answer. I'm not sure everyone understands that you can pass an Image inside a string for Text. – Berry Blue Feb 12 '23 at 21:00

1 Answers1

2

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

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52