【发布时间】:2022-01-05 19:18:54
【问题描述】:
我正在构建一个使用按钮对各种列表进行排序的应用。
我正在尽最大努力尽可能 DRYly 遵循 MVVM 设计模式。有几个视图显示列表,所以我希望能够在多个视图中重用按钮结构,并将它们连接到多个视图模型
我目前设置代码的方式是构建,但按下新按钮时列表不会改变。有什么想法吗?
可以从 GitHub 下载有问题的示例项目:https://github.com/sans-connaissance/SOQ-BetterButtons
这是视图的代码:
import SwiftUI
struct ContentView: View {
@StateObject private var vm = ContentViewModel()
var body: some View {
VStack {
HStack {
SortButton(name: .arrayOne, bools: $vm.bools)
.onChange(of: vm.bools){ _ in vm.getArray()}
SortButton(name: .arrayTwo, bools: $vm.bools)
.onChange(of: vm.bools){ _ in vm.getArray()}
SortButton(name: .arrayThree, bools: $vm.bools)
.onChange(of: vm.bools){ _ in vm.getArray()}
}
List {
ForEach(vm.contentArray, id: \.self) { content in
Text(content.self)
}
}
}
.onAppear {vm.setButtons()}
.onAppear {vm.getArray()}
}
}
这是按钮的代码
import SwiftUI
struct SortButton: View {
var name: Select
@Binding var bools: [String : Bool]
var body: some View {
Button {
func show(button: Select) {
Select.allCases.forEach { button in
bools[button.rawValue] = false
}
bools[button.rawValue] = true
}
} label: {
Text(name.rawValue)
}
}
}
enum Select: String, CaseIterable {
case arrayOne = "arrayOne"
case arrayTwo = "arrayTwo"
case arrayThree = "arrayThree"
}
最后是本示例的 ViewModel。
import Foundation
class ContentViewModel: ObservableObject {
@Published var contentArray = [String]()
@Published var bools = [String : Bool]()
private let arrayOne = ["One", "Two", "Three"]
private let arrayTwo = ["Four", "Five", "Six"]
private let arrayThree = ["Seven", "Eight", "Nine"]
func setButtons() {
Select.allCases.forEach { button in
bools[button.rawValue] = false
}
bools["arrayOne"] = true
}
func getArray() {
if bools["arrayOne"]! {
contentArray.removeAll()
contentArray.append(contentsOf: arrayOne)
}
if bools["arrayTwo"]! {
contentArray.removeAll()
contentArray.append(contentsOf: arrayTwo)
}
if bools["arrayThree"]! {
contentArray.removeAll()
contentArray.append(contentsOf: arrayThree)
}
}
}
GitHub 上的示例项目链接: https://github.com/sans-connaissance/SOQ-BetterButtons
感谢观看!!
【问题讨论】:
标签: ios swift button mvvm swiftui