Home > other >  How can i return images from assets instead of systemName Image and call it in the body Using swiftu
How can i return images from assets instead of systemName Image and call it in the body Using swiftu

Time:08-13

How can i return images from assets instead of systemName Image and call it in the body Using swiftui

var sfSymbol: String {
        switch self {
        case .info:
         return "info.circle"
        case .success:
            return "checkmark.seal"
        case .warning:
            return "exclamationmark.octagon"
        case .error:
            return "xmark.octagon"
        }
    }

 Image.init(systemName: data.type.sfSymbol)

CodePudding user response:

You can do it with an Image Set, an @ViewBuilder.

struct CustomImageView: View {
    var body: some View {
        Symbols.info.image()
    }
    enum Symbols: String, CaseIterable{
        case info
        case success
        case warning
        case error
        var sfSymbolName: String{
            switch self {
            case .info:
                return "info.circle"
            case .success:
                return "checkmark.seal"
            case .warning:
                return "exclamationmark.octagon"
            case .error:
                return "xmark.octagon"
            }
        }
        ///Name must exactly match an `Image Set` in `Assets`
        ///Project Navigator > Assets >   > Image Set >
        var assetsName: String{
            switch self {
            case .info:
                return "NameFromAssetsImageSet_info"
            case .success:
                return "NameFromAssetsImageSet_success"
            case .warning:
                return "NameFromAssetsImageSet_warning"
            case .error:
                return "NameFromAssetsImageSet_error"
            }
        }
        
        @ViewBuilder func image() -> some View {
            let showFromAssets: Bool = true
            switch showFromAssets{
            case true:
                Image(assetsName)
            case false:
                Image(systemName: sfSymbolName)
            }
        }
    }
}

CodePudding user response:

If you want to use asset images, you have to use Image("") not Image(systemName: "") because the Image(systemName: "") is for SF Symbols.

Say your image in the asset with name "Swift", just call it like this in your body:

Image("Swift")

or

Image(myStringVariable) 

myStringVariable is a @State var that you set its value depends on the given condition

  • Related