SwiftUI-将ListStyle封装在枚举中,并将其转换回ListStyle [英] SwiftUI - Wrap ListStyle in an enum and translate it back to ListStyle

查看:129
本文介绍了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

无法推断出通用参数'S'

Generic parameter 'S' could not be inferred

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 {

推荐答案

您可以返回

List {
    // ...
}
.listStyle(for: options.listStyle)

这篇关于SwiftUI-将ListStyle封装在枚举中,并将其转换回ListStyle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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