Home > Software design >  SwiftUI: Extending the Image type to return an image processed through a method
SwiftUI: Extending the Image type to return an image processed through a method

Time:12-02

This approach does not work for me and I can't figure out how to do it.


extension Image {
    func getResizedImage(_ imageName: String) -> any View {
        return Image(imageName)
            .resizable()
    }
}

// then ...

struct ContentView: View {
    var body: some View {
        Image.getResizedImage("myImageFromAssets")
    }
} ```

CodePudding user response:

Two issues:

  1. Because you're calling this on Image, you need a static function

  2. The function should return some View, not any View

extension Image {
    static func getResizedImage(_ imageName: String) -> some View {
        return Image(imageName)
            .resizable()
    }
}

struct ContentView: View {
    var body: some View {
        Image.getResizedImage("myImageFromAssets")
    }
}
  • Related