Prevent ScrollView from Shrinking Content SwiftUI

334 Views Asked by At

I have a Horizontal ScrollView with some Content received from an API. However, when I scroll the Content, after a certain amount of Scrolling, the content shrinks. Is there a way to prevent this? The 2nd Image shows the content Shrinking after scrolling.

Normal View

ScrollView Content Getting Shrunk

My Code is as Follows:

 ScrollView(.horizontal){
                        LazyHStack(alignment:.center, spacing: 5){
                            
                           
                                ForEach(recipe?.extendedIngredients ?? [], id: \.self){ extendedIngredient in
                                    
                                    VStack(spacing:4){
                                        AsyncImage(url: URL(string: "https://spoonacular.com/cdn/ingredients_100x100/" + (extendedIngredient.image ?? "apple.jpg") )) { image in
                                            image
                                                .resizable()
                                                .scaledToFit()
                                                //.frame(width:100, height: 100)
                                        } placeholder: {
                                            ProgressView()
                                                .tint(.gray)
                                        }
                                        
                                        Text(extendedIngredient.name ?? "Unknown")
                                        
                                    }//Inner VStack
                                    
                                
                                }//ForEach
                        }
                        
                      }//Inner ScrollView

Update-- I added a frame modifier with a Height of 150 to the LazyHStack and that seemed to have solved the issue. However, is the the right way to get around this issue?

1

There are 1 best solutions below

0
hoangnam714 On

The problem is the image itself, it is stretched to full size. When you set a height for it, it will stretch the image to that height. In fact, if the image has a height that is too large (larger than the screen height), we have to crop the image or you can use a small trick as follows:

Color.white
    .overlay(
        Image("Image name")
            .resizable()
            .scaledToFill()
    )
    .frame(maxWidth: .infinity)
    .frame(height: 211) // or .cliper() if image height or width is too large