How to store a property that conforms to the ListStyle protocol

雨燕双飞 提交于 2021-01-28 07:32:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!