Home > OS >  How to have UIImage display a color by default?
How to have UIImage display a color by default?

Time:05-05

I want to have a UIImage in my app that is not optional so that when it is changed all the views that display that image (with swiftUI Image()) in my app automatically update with the real image. How can I set my UIImage as a default gray color until it is updated/changed in SessionStore with new data from a network call, or setting a new picture in SessionStore, etc...

I am using this UIImage in my SwiftUI view as an Image(), I would think this means converting UIColor to data somehow?

Thank you

class SessionStore: ObservableObject {

    @Published var profilePicture: UIImage = UIImage(data: <GRAY-COLOR-DATA??>)

}
struct ContentView : View {
    @EnvironmentObject var session: SessionStore
    
    var body: some View {
        VStack {
            Image(uiImage: session.profilePicture) 
        }
    }
}

CodePudding user response:

I recommend keep image optional, but show default grey color right in view, like (but not limited to):

class SessionStore: ObservableObject {
    @Published var profilePicture: UIImage?
}

struct ContentView : View {
    @EnvironmentObject var session: SessionStore
    
    var body: some View {
        VStack {
          if let image = session.profilePicture {
            Image(uiImage: image)
          } else {
            Color.grey
          } 
        }
    }
}
  • Related