目前,我正在用listStyle修饰符设置.listStyle(InsetGroupedListStyle())。
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())
}
}我想在ListView中创建一个属性来存储ListStyle。问题是ListStyle是一种协议,我得到:
协议'ListStyle‘只能用作泛型约束,因为它具有自或关联的类型要求
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)
}
}我看了这个question,但我不知道ListStyle的associatedtype是什么。
发布于 2020-10-18 22:24:11
您可以使用泛型使您的listStyle成为某种ListStyle类型:
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
复制相似问题