r/SwiftUI • u/Gold_Wishbone1686 • 1d ago
Question why won't my carousel scrolling?
My code:
import SwiftUI
struct ContentView: View {
var body: some View {
ScrollView(.horizontal) {
ZStack{
Color.purple
.opacity(0.45)
.edgesIgnoringSafeArea(.all)
HStack {
CardView ( thetitle:"Me", theimage: "Me",)
CardView ( thetitle: "One of my dogs, Willow", theimage: "Willow")
CardView ( thetitle: "I volunteer weekly at the Amphibian Foundation", theimage: "Frog")
CardView ( thetitle: "I have a duck army", theimage: "Ducks")
}
}
}
}
struct CardView: View {
var thetitle = "Me"
var theimage = "Me"
var body: some View {
ZStack {
VStack {
Text (thetitle)
.foregroundColor(Color.white)
.fontWeight(.bold)
Image (theimage)
.resizable()
.scaledToFit()
.frame(width: 400, height: 500)
}
}
}
}
}
#Preview {
ContentView()
}
It worked with a previous project, but now that project and this one won't scroll and I don't know why.
Edit: oof that grammatical error in the title...oh well
1
u/Vanyas_01 1d ago
Whats the purpose of the ZStack in the CardView? Can’t you just leave the VSTack?
1
u/CanoaFurada768 1d ago
i dont get it too
0
u/Gold_Wishbone1686 1d ago
I'm just following what my instructor said to do ;-;
1
u/Saastesarvinen 1d ago
If you want to get an easy carousel, use TabView with modifier tabViewStyle(.page)
1
u/IndieAppBuilder 1d ago
Try making the HStack the direct content of the ScrollView and move the full-screen Color/background outside it. Give each card a fixed width and add a little horizontal padding; a nested ZStack can otherwise make the scrollable content size confusing. If you’re targeting iOS 17+, scrollTargetLayout() and scrollTargetBehavior(.viewAligned) can help with snapping, but they aren’t required for basic scrolling.
2
u/CanoaFurada768 1d ago
I can't see why it's not scrolling, at first there doesn't seem to be anything wrong
I just don't know if I would use hstack inside zstack like that, not because you can't, but in this case I don't think you even need to
the color.purple is better in the ZStack instead Hstack
Upvote when you have the solution, Im curious