iosswiftui

How can we pass dynamic images in SwiftUI view?


My code

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            accessoryImage
            Text("Hello, world!")
        }
        .padding()
    }
    
    var accessoryImage: Image? {
        return Image(systemName: "globe")
            .imageScale(.large)
            .foregroundStyle(.tint) as? Image
    }
}

#Preview {
    ContentView()
}

My image is never seen. What am I doing wrong, should we add foregroundColor using view modifier.


Solution

  • You're trying to cast a modified Image view as an Image, but once you apply modifiers like .imageScale() or .foregroundStyle(), it becomes a modified view (ModifiedContent), not a plain Image anymore. So the cast as? Image fails, and accessoryImage becomes nil.

    so how can we fix this

    Instead of returning an optional Image?, return a some View or just use the image inline.like this

    var accessoryImage: some View {
        Image(systemName: "globe")
            .imageScale(.large)
            .foregroundStyle(.tint)
    }
    

    If you really need Image?, don’t apply modifiers in the computed property like this

    var accessoryImage: Image? {
        return Image(systemName: "globe")
    }
    

    instead apply modifier like this

    accessoryImage?
        .imageScale(.large)
        .foregroundStyle(.tint)