Image doesn't appear with AsyncImage in SwiftUI
Asked Answered
N

3

6

I have AsyncImage inside a TabView. When I do this the image never appears. I just see the progress bar.

@available(iOS 15.0, *)
struct TEST: View {
    var body: some View {
        VStack {
            TabView {
                AsyncImage(url: URL(string: "https://blckbirds.com/wp-content/uploads/2021/10/pexels-kammeran-gonzalezkeola-6128227-2.jpg"), scale: 2) { image in
                    image
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                } placeholder: {
                    ProgressView()
                        .progressViewStyle(.circular)
                }

            }.tabViewStyle(PageTabViewStyle(indexDisplayMode: .automatic))
        }
    }
}
Nosewheel answered 10/11, 2021 at 6:0 Comment(0)
H
13

try using a ZStack to wrap the AsyncImage, like this, works for me:

struct TEST: View {
    
    var body: some View {
        VStack {
            TabView {
                ZStack {   // <--- here
                    AsyncImage(url: URL(string: "https://blckbirds.com/wp-content/uploads/2021/10/pexels-kammeran-gonzalezkeola-6128227-2.jpg"), scale: 2) { image in
                        image
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                    } placeholder: { ProgressView().progressViewStyle(.circular) }
                }
            }.tabViewStyle(PageTabViewStyle(indexDisplayMode: .automatic))
        }
    }
    
}
Hoarse answered 10/11, 2021 at 6:28 Comment(2)
Yup, that worked. Just that simple. Thanks!Nosewheel
That didnt work for me. I wonder why. That is very weird...Billye
C
0

I am new to SwiftUI. I copied the @workingdog support's code and it worked well. But I think there is some glitch with the preview and I am not sure this an unknown issue or not.

With the original code, I can only see the loading view, not matter I close and re-open the preview window. Then I added a frame for the image view. I can see the image being properly loaded by changing frame size to something else then change it back, e.g. 300 -> 350 -> 300.

struct ExampleImgItem: View {
    var body: some View { 
    `workingdog support`'s code
}


struct ExampleImgItem_Previews: PreviewProvider {
    static var previews: some View {
        ExampleImgItem()
            .frame(width: 300, height: 300, alignment: .leading)
    }
}


P.S. I am using Xcode 13.3.1, 
Cuccuckold answered 9/12, 2022 at 19:28 Comment(0)
U
0

Got the same issue. My solution is to add

.aspectRatio(CGSize(width: 6, height: 9), contentMode: .fill)
.scaledToFit()

to TabView.

Ullman answered 21/1, 2023 at 3:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.