简体   繁体   English

如何存储符合 ListStyle 协议的属性

[英]How to store a property that conforms to the ListStyle protocol

Currently I'm setting the listStyle with the .listStyle(InsetGroupedListStyle()) modifier.目前我正在使用.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())
    }
}

I want to make a property inside ListView to store the ListStyle .我想在ListView创建一个属性来存储ListStyle The problem is that ListStyle is a protocol, and I get:问题是ListStyle是一个协议,我得到:

Protocol 'ListStyle' can only be used as a generic constraint because it has Self or associated type requirements协议“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)
    }
}

I looked at this question , but I don't know what ListStyle 's associatedtype is.我看了这个问题,但我不知道ListStyleassociatedtype是什么。

You can use generics to make your listStyle be of some ListStyle type:您可以使用泛型使您的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM