【问题标题】:SwiftUI picker not changing selection with an EnumSwiftUI 选择器不使用枚举更改选择
【发布时间】:2021-03-29 15:27:35
【问题描述】:

我正在尝试将 Enum 与 SwiftUI 选择器一起使用,但无法让选择器更新所选值。不太确定我做错了什么。

enum WindowLayout: String, Equatable, Codable, CaseIterable, Identifiable {
    case oneByOne = "1 x 1"
    case oneByTwo = "1 x 2"
    case oneByThree = "1 x 3"
    case twoByOne = "2 x 1"
    case twoByTwo = "2 x 2"
    case twoByThree = "2 x 3"
    case threeByOne = "3 x 1"
    case threeByTwo = "3 x 2"
    
    var id: WindowLayout {
        self
    }
    
    var rows: Int {
        switch self {
        case .oneByOne, .oneByTwo, .oneByThree:
            return 1
        case .twoByOne, .twoByTwo, .twoByThree:
            return 2
        case .threeByOne, .threeByTwo:
            return 3
        }
    }
    
    var columns: Int {
        switch self {
        case .oneByOne, .twoByOne, .threeByOne:
            return 1
        case .oneByTwo, .twoByTwo, .threeByTwo :
            return 2
        case .oneByThree, .twoByThree :
            return 3
        }
    }
}


struct WindowCommands: Commands {
    @ObservedObject var viewModel = GridConfigViewModel(windowLayout: WindowLayout.oneByOne)
    var body: some Commands {
        CommandMenu("Video") {
            Picker(selection: $viewModel.windowLayout, label: Text("Window Configuration")) {
                ForEach(WindowLayout.allCases, id: \.id) {
                    Text($0.rawValue).tag($0)
                }
            }
        }
    }
}

class GridConfigViewModel: ObservableObject {
    @Published public var windowLayout: WindowLayout {
        didSet {
            print("set \(windowLayout.rawValue)")
        }
    }
    
    init(windowLayout: WindowLayout) {
        self.windowLayout = windowLayout
    }
}

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    在 WindowCommand 的调用方而不是在 WindowCommand 内部创建包装在 @Publisher 中的 viewModel。该调用者应该是 ObservableObject。

    @ObservedObject 是 WindowCommand 中属性的正确包装器,但它们在上面的方式意味着每次调用 WindowCommand 时都会实例化它。

    @Published var gridViewModel =  GridConfigViewModel(windowLayout: WindowLayout.oneByOne)
    

    ...然后调用WindowCommands的地方...

    WindowCommand(viewModel: gridViewModel)
    

    【讨论】:

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