SwiftUI: How to display one image at a time?

410 views Asked by At

I have an array of images which I loop through, and display in a scrollView. This is want I want to achieve:

  1. I would like there to only be one visible image at a time. Like TikTok and instagram.
  2. I would like the image to take up as much of the screen as possible, while still keeping the aspectRatio.
  3. Center image
  4. I don’t mind using .edgesIgnoringSafeArea([.top, .leading, .trailing])

This is the code I have so far. As you can see there is two images visible at a time. And even when there is only one image in the array, it isn’t centered, but clings to the top of the screen.

Any ideas on how to solve this?

 ScrollView(.vertical) {
            ForEach(allRetrievedMedia, id: \.self) { item in
                switch(item) {
                case .image(let img):

                        Image(uiImage: img)
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(alignment: .center)
   
                }
            }
        }

Image of screen

1

There are 1 answers

0
scraptechguy On

Embed the image in a container and add .frame(width: screenSize.width, height: screenSize.height, alignment: .center) to that container. Then add .scaledToFill() method to the image itself. This should do the trick, here's a snippet to help...

struct ContentView: View {
    let screenSize: CGRect = UIScreen.main.bounds

    var body: some View {
        ScrollView(.vertical) {
            ForEach(allRetrievedMedia, id: \.self) { item in switch(item) {
                case .image(let img):
                VStack {
                    Image(uiImage: img)
                        .resizable()
                        .scaledToFill()
                }.frame(width: screenSize.width, height: screenSize.height, alignment: .center)
            }
        }
    }
}

Haven't tried that myself, but should work like a charm. Hope it helps