[英]How to store a property that conforms to the ListStyle protocol
目前我正在使用.listStyle(InsetGroupedListStyle())
修饰符设置listStyle
。
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”只能用作通用约束,因为它具有 Self 或关联类型要求
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)
}
}
我看了这个问题,但我不知道ListStyle
的associatedtype
是什么。
您可以使用泛型使您的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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.