Daniel Jeong
Daniel Jeong

Reputation: 33

Combining 2 ScrollViews in Swift

I'm trying to connect 2 views. One is a ScrollView and the other is a List. Does anyone know how to do that? Putting both into a singular ScrollView doesn't work, and calling APIResponseView().environmentObject(Model()) inside of ContentView() also doesn't work.

struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            VStack{
                ContentView() // this is a ScrollView
                APIResponseView().environmentObject(Model()) // this is a List
            }
        }
    }
}

As you can see, the views aren't connected: Image found here

Upvotes: 0

Views: 732

Answers (1)

ChrisR
ChrisR

Reputation: 12115

If you want to have the ScrollView move out of view when scrolling the list, you have to put the ScrollView INSIDE the list:

enter image description here

struct ContentView: View {
    
    @State private var test = false
    
    var body: some View {
        
        // List
        List {
            // ScrollView
            ScrollView(.horizontal) {
                HStack {
                    ForEach(0..<6) { i in
                        
                        Text("ScrollView \(i)")
                            .frame(width: 150, height: 200)
                            .background(
                                RoundedRectangle(cornerRadius: 10)
                                    .fill(.blue)
                            )
                    }
                }
            }
            
            ForEach(0..<10) { item in
                HStack {
                    VStack {
                        Text("Overheadline")
                            .font(.caption)
                            .foregroundColor(.secondary)
                        Text("List Item \(item)")
                    }
                    Spacer()
                    RoundedRectangle(cornerRadius: 10)
                        .fill(.gray)
                        .frame(width: 50, height: 50)
                }
            }
        }
        .listStyle(.plain)
    }
}

Upvotes: 2

Related Questions