Search code examples
swiftxcodeswiftuiios13

Problem with self sizing Image embedded in NavigationButton. It turns blue


I have a strange problem, where if an resizable image that I made (a custom view) is not in NavigationButton, then it works normally, but if it is in it, then the image is still sized well, but it becomes fully blue. Does anyone know what is wrong?

struct DynamicallyResizableImage: View {
    let imageName: String
    let height: CGFloat
    let width: CGFloat

    init(imageName: String, height: CGFloat? = nil, width: CGFloat? = nil) {
        self.imageName = imageName
        let imageSize = UIImage(named: imageName)!.size

        guard let height = height else {
            if let width = width {

                self.width = width
                self.height = imageSize.height * (width/imageSize.width)
                return
            }
            self.height = 0
            self.width = 0
            return
        }

        if let width = width {
            self.height = height
            self.width = width
            return
        }

        self.height = height
        self.width = imageSize.width * (height/imageSize.height)
    }

    var body: some View {
        Image(imageName)
            .resizable()
            .frame(width: width, height: height)
    }

}
NavigationButton(destination: PicturePreviewView(imageName: "IMG_4955")) {
                        DynamicallyResizableImage(imageName: "IMG_4955", height: 200)
                    }

When not embedded in NavigationButton, everything works great. When embedded in NavigationButton, the image becomes gets filled with blue color.

Anyone knows how to fix it? Thanks!!!


Solution

  • So I fixed it with a help of a fellow redditor. Inside off the custom view I had to add a renderingMode to the Image just like that:

    Image(imageName)
                .renderingMode(.original)
                .resizable()
                .frame(width: width, height: height)