ios – Swift UI Center Image that is rendered asynchronously


I want to position an image in the center of the screen. I am using KFImage which is from the KingFisher library to render and display images from the web. These images are not instantly rendered so the onAppear method isn’t always sufficient to calculate the image size. Using 2 spacers in a VStack also doesn’t work. And setting the alignment to center also doesn’t work. My method below works very well for UIImages but due to the fact that the image may not be rendered when the onAppear executes, it fails sometimes. How can I center the image?

                     KFImage(URL(string: image))
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .offset(x: (screenWidth() - imageWidth) / 2.0, y: (screenHeight() - imageHeight) / 2.0)
                            .background (
                                GeometryReader { proxy in
                                    Color.clear
                                        .onAppear {
                                            imageHeight = proxy.size.height
                                            imageWidth = proxy.size.width
                                        }
                                        .onChange(of: currentStory) { _ in
                                            imageHeight = proxy.size.height
                                            imageWidth = proxy.size.width
                                        }
                                }
                            )

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img