How do a create a reusable simple custom list style with my own color and spacing

53 views Asked by At

I want all the lists in my application to look exactly the same and don't want to respecify all these settings over and over. I get the following error: Cannot find type 'Configuration' in scope. I currently have something like this:

struct CustomListStyle: ListStyle {
    func makeBody(configuration: Configuration) -> some View {
        ScrollView {
            VStack(spacing: 10) {
                ForEach(configuration.data, id: \.self) { item in
                    Text(item as? String ?? "")
                        .foregroundColor(.blue)
                        .padding(10) 
                        .background(Color.gray) 
                        .cornerRadius(10)
                }
            }
            .padding() 
        }
    }
}

struct ContentView: View {
    var body: some View {
        List(0..<10, id: \.self) { index in
            Text("Item \(index)")
        }
        .listStyle(CustomListStyle())
    }
}

Edit - 1 - Here is one for reference

List( selection: $dm.someVar ) {
    Section( ) {
        LazyVGrid(columns: [
            GridItem(.flexible(minimum: 120)),
        ], alignment: .leading, spacing: 10) {
            ForEach(0..<20, id: \.self) { index in
                Text("Column1 abcdef: \(index)")
            }
        }
    }
}
1

There are 1 answers

2
Benzy Neez On BEST ANSWER

If you try to implement a ListStyle, you can let Xcode add stubs for protocol conformance. You will then see, that the required functions all start with _. This is a clue, that the protocol ListStyle is not intended to be used for custom implementations.

However, you might be able to achieve what you're after by creating a wrapper for a List that accepts a ViewBuilder as parameter. Something like:

struct CustomList<Content>: View where Content: View {
    @ViewBuilder let content: () -> Content
    var body: some View {
        List {
            content()
                .listRowBackground(
                    Color.yellow
                        .clipShape(RoundedRectangle(cornerRadius: 10))
                )
        }
        .listStyle(.plain)
        .listRowSpacing(10)
        .foregroundStyle(.pink)
        .padding()
        .background(.gray)
    }
}

struct ContentView: View {
    var body: some View {
        CustomList {
            ForEach(0..<100, id: \.self) { item in
                Text("Item \(item)")
            }
        }
    }
}

Screenshot