本文介绍了SwiftUI-将ListStyle封装在枚举中,并将其转换回ListStyle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个库,所以我希望它尽可能地易于配置.我将所有可配置选项放在SupportOptions
中.
I'm working on a library, so I want it to be as easily configurable as possible. I put all the configurable options inside SupportOptions
.
struct SupportOptions {
var text: String = ""
var listStyle: CustomListStyle = CustomListStyle.insetGroupedListStyle
}
extension SupportOptions {
/**
Enum wrapper for `ListStyle`
*/
enum CustomListStyle {
case defaultListStyle
case plainListStyle
case groupedListStyle
case insetGroupedListStyle
case insetListStyle
case sidebarListStyle
}
}
我正在按照 @Sweeper的建议使用枚举存储ListStyle
,所以这就是CustomListStyle
是为了.但是我需要将CustomListStyle
转换为实际的ListStyle
.这是我到目前为止的内容:
I'm following @Sweeper's suggestion to use an enum to store ListStyle
, so that's what CustomListStyle
is for. But I need to translate CustomListStyle
to an actual ListStyle
. This is what I have so far:
extension List {
func getStyle<S>(listStyle: SupportOptions.CustomListStyle) -> S {
switch listStyle {
case .defaultListStyle:
return DefaultListStyle() as! S
case .plainListStyle:
return PlainListStyle() as! S
case .groupedListStyle:
return GroupedListStyle() as! S
case .insetGroupedListStyle:
return InsetGroupedListStyle() as! S
case .insetListStyle:
return InsetListStyle() as! S
case .sidebarListStyle:
return SidebarListStyle() as! S
}
}
}
但是当我使用它时,我会得到
But when I use it, I get
struct ContentView: View {
let options = SupportOptions(listStyle: .defaultListStyle)
let data = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen"]
var body: some View {
List { /// Error! Generic parameter 'S' could not be inferred
ForEach(data, id: \.self) { word in
Text(word)
}
}
.getStyle(listStyle: options.listStyle)
}
}
我尝试添加占位符类型S
,但是错误保持不变...
I tried adding a placeholder type S
, but the error stayed the same...
struct ContentView<S>: View where S: ListStyle {
推荐答案
您可以返回不透明类型(some View
)代替:
extension List {
@ViewBuilder
func listStyle(for customListStyle: SupportOptions.CustomListStyle) -> some View {
switch customListStyle {
case .defaultListStyle:
listStyle(DefaultListStyle())
case .plainListStyle:
listStyle(PlainListStyle())
case .groupedListStyle:
listStyle(GroupedListStyle())
case .insetGroupedListStyle:
listStyle(InsetGroupedListStyle())
case .insetListStyle:
listStyle(InsetListStyle())
case .sidebarListStyle:
listStyle(SidebarListStyle())
}
}
}
List {
// ...
}
.listStyle(for: options.listStyle)
这篇关于SwiftUI-将ListStyle封装在枚举中,并将其转换回ListStyle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!