【问题标题】:onChange(of: perform:) with enums not working in swiftuionChange(of: perform:) 枚举在 swiftui 中不起作用
【发布时间】:2021-08-07 10:00:24
【问题描述】:

以下代码应在选项卡更改时打印值,但未按预期打印。 如果我使用选定的数据类型(如 Int 或字符串而不是枚举),则相同的代码可以正常工作。

我是否需要确认枚举才能使这项工作正常进行?

enum Tab: String, Codable, Comparable {
    static func < (lhs: Tab, rhs: Tab) -> Bool {
        lhs.rawValue < rhs.rawValue
    }
    
    case firstTab
    case secondTab
    case thirdTab
}

struct ContentView: View {
 
    @State var selected: Tab = .firstTab
    var body: some View {
        TabView(selection: $selected) {
            Text("first tab")
                .tabItem {
                    Text(Tab.firstTab.rawValue)
                }.tag(Tab.firstTab.rawValue)
               
            Text("second tab")
                .tabItem {
                    Text(Tab.secondTab.rawValue)
                }.tag(Tab.secondTab.rawValue)
            Text("third tab")
                .tabItem {
                    Text(Tab.thirdTab.rawValue)
                }.tag(Tab.thirdTab.rawValue)
        }.onChange(of: selected, perform: { value in
            print(value)
        })
    }
}

提前致谢

【问题讨论】:

    标签: swift enums swiftui swiftui-tabview


    【解决方案1】:

    删除每个标签的.rawValue,因为您的 TabView 使用枚举大小写进行选择,而不是您的大小写字符串 (.rawValue)

    TabView(selection: $selected) {
        Text("first tab")
            .tabItem {
                Text(Tab.firstTab.rawValue)
            }.tag(Tab.firstTab) //< -Here
        
        Text("second tab")
            .tabItem {
                Text(Tab.secondTab.rawValue)
            }.tag(Tab.secondTab) //< -Here
        Text("third tab")
            .tabItem {
                Text(Tab.thirdTab.rawValue)
            }.tag(Tab.thirdTab) //< -Here
    

    我是否需要确认枚举才能使这项工作正常进行?

    没有。无需再确认。

    简单点

    enum Tab: String {
        case firstTab
        case secondTab
        case thirdTab
    }
    

    【讨论】:

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