如何存储符合 ListStyle 协议的属性 [英] How to store a property that conforms to the ListStyle protocol

查看:47
本文介绍了如何存储符合 ListStyle 协议的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在使用 .listStyle(InsetGroupedListStyle()) 修饰符设置 listStyle.

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())
    }
}

我想在 ListView 中创建一个属性来存储 ListStyle.问题是 ListStyle 是一个协议,我得到:

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

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

我看了这个问题,但我不知道ListStyle是什么关联类型 是.

I looked at this question, but I don't know what ListStyle's associatedtype is.

推荐答案

你可以使用泛型让你的 listStyle 成为 some ListStyle类型:

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

这篇关于如何存储符合 ListStyle 协议的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆