问题
Currently I'm setting the listStyle
with the .listStyle(InsetGroupedListStyle())
modifier.
struct ContentView: View {
var body: some View {
ListView()
}
}
struct ListView: View {
let data = ["One", "Two", "Three", "Four", "Five", "Six"]
var body: some View {
List {
ForEach(data, id: \.self) { word in
Text(word)
}
}
.listStyle(InsetGroupedListStyle())
}
}
I want to make a property inside ListView
to store the ListStyle
. The problem is that ListStyle
is a protocol, and I get:
Protocol 'ListStyle' can only be used as a generic constraint because it has Self or associated type requirements
struct ContentView: View {
var body: some View {
ListView(listStyle: InsetGroupedListStyle())
}
}
struct ListView: View {
var listStyle: ListStyle /// this does not work
let data = ["One", "Two", "Three", "Four", "Five", "Six"]
var body: some View {
List {
ForEach(data, id: \.self) { word in
Text(word)
}
}
.listStyle(listStyle)
}
}
I looked at this question, but I don't know what ListStyle
's associatedtype
is.
回答1:
You can use generics to make your listStyle
be of some ListStyle
type:
struct ListView<S>: View where S: ListStyle {
var listStyle: S
let data = ["One", "Two", "Three", "Four", "Five", "Six"]
var body: some View {
List {
ForEach(data, id: \.self) { word in
Text(word)
}
}
.listStyle(listStyle)
}
}
来源:https://stackoverflow.com/questions/64418888/how-to-store-a-property-that-conforms-to-the-liststyle-protocol