代码之家  ›  专栏  ›  技术社区  ›  aheze But I'm Not A Wrapper Class

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

  •  1
  • aheze But I'm Not A Wrapper Class  · 技术社区  · 4 年前

    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”只能用作泛型约束,因为 它有自己的或相关的类型要求

    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 ,但我不知道是什么 列表样式 associatedtype 是。

    1 回复  |  直到 4 年前
        1
  •  2
  •   pawello2222    4 年前

    你可以使用泛型 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)
        }
    }