1 year ago

#71393

test-img

kAiN

Optimizing an image in a horizontal scrollview

Hi all I'm trying to create a horizontal image slider using swiftui. I'm having trouble viewing the images because they don't fit properly and I don't know why.

As you can see from the image it appears that the first photo is not as wide as the device. In a nutshell it looks as if the photo is eventually cropped from the next photo .. Where am I wrong?

enter image description here

struct FeaturedWorksModel: Identifiable {
    var id = UUID()
    var image: String
    var title: String
}

var featuredWorksItems: [FeaturedWorksModel] = [
    FeaturedWorksModel(image: "slider1", title: "TAGLIO CREATIVO"),
    FeaturedWorksModel(image: "slider4", title: "LOREM IPSUM"),
    FeaturedWorksModel(image: "slider3", title: "NEQUE EST DOLOR"),
    FeaturedWorksModel(image: "slider2", title: "CONSECTETUR, INTEGER ERAT AUGUE ")
]

struct FeaturedWorksItemView: View {
    let featuredWorks: FeaturedWorksModel
    var body: some View {
        Image(featuredWorks.image)
            .resizable()
            .scaledToFill()
    }
}

struct HomeView: View {
    var body: some View {
        ZStack(alignment: .top) {
            Color.background.edgesIgnoringSafeArea(.all)
            ScrollView(.vertical, showsIndicators: false) {
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack(spacing: 0) {
                        ForEach(featuredWorksItems) { works in
                            FeaturedWorksItemView(featuredWorks: works)
                        }.frame(width: screen.width)
                    }
                }
            }
            .edgesIgnoringSafeArea(.all)
        }
    }
}

extension View {
    var screen: CGRect { UIScreen.main.bounds }
}

UPDATE

I tried to change .frame (width: screen.width) to .frame (maxWidth: .infinity) as per the suggestion but now as you can see from the photo, now I get a larger width of the device

enter image description here

ios

swift

image

swiftui

scrollview

0 Answers

Your Answer

Accepted video resources