1

I am trying to build out a custom scroll view that can take in different cells I have created and present those in the scroll view. I cannot figure out how to pass a generic SwiftUI view into the constructor of my custom scroll view struct, is it possible to do this? some like this:

struct CustomScroll<Content: View>: View {
      var genericCell: View

      var body: some View {
        VStack(spacing: 10) {
            ForEach(0...7, id: \.self){ index in
                VStack(spacing: 10){
                    cell
                }
            }
        }
    }

}
3
  • 4
    Try replacing var genericCell: View with var genericCell: Content Commented Feb 25, 2022 at 16:51
  • @aheze is it possible to use [Content] Commented Feb 25, 2022 at 16:59
  • This might help: stackoverflow.com/questions/62730374/… Commented Feb 25, 2022 at 17:03

2 Answers 2

4

I suppose you're looking for something like this:

struct CustomScroll<Content: View>: View {
    
    @ViewBuilder let content: () -> Content
    
    var body: some View {
        ScrollView {
            VStack(spacing: 10) {
                content()
            }
        }
    }
}

and use it e.g. like this:

struct ContentView: View {
    var body: some View {
        CustomScroll {
            Text("Test 1")
            Text("Test 2")
            Text("Test 3")
            Text("Test 4")
            Text("Test 5")
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can créate a custom Cell for that!

struct CustomCellView: View {
var object: Object = Object(nombre: "")
init(m: Object) {
    object = m
}
var body: some View {
    VStack {
        HStack {
            Text(object.descripcion).font(.system(size: 11)).frame(width: 105, alignment: .trailing)
        }
        Divider()
    }
}

}

And then call that in the scroll View

 ForEach(objects, id: \.objectId) { object in
                    CustomCellView(m: object)
                }.padding(EdgeInsets(top: 3, leading: 0, bottom: 0,   trailing: 0))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.