【问题标题】:How to store a property that conforms to the ListStyle protocol如何存储符合 ListStyle 协议的属性
【发布时间】:2020-10-18 22:21:35
【问题描述】:

目前我正在使用.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 是一个协议,我得到:

Protocol '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)
    }
}

我看了这个question,但我不知道ListStyleassociatedtype是什么。

【问题讨论】:

    标签: ios swift swiftui protocols


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多