[ad_1]
I am constructing an app that makes use of buttons to kind quite a lot of lists.
I am making an attempt my greatest to comply with the MVVM design sample as DRYly as attainable. There are a number of Views that show lists and so I might like to have the ability to reuse button structs in numerous views, and join them to numerous View Fashions
The way in which I presently have this setup the code Builds however the lists don’t change when a brand new button is pressed. Any concepts?
A pattern mission with the problem might be downloaded from GitHub right here: https://github.com/sans-connaissance/SOQ-BetterButtons
This is the code for the View:
import SwiftUI
struct ContentView: View {
@StateObject non-public var vm = ContentViewModel()
var physique: some View {
VStack {
HStack {
SortButton(title: .arrayOne, bools: $vm.bools)
.onChange(of: vm.bools){ _ in vm.getArray()}
SortButton(title: .arrayTwo, bools: $vm.bools)
.onChange(of: vm.bools){ _ in vm.getArray()}
SortButton(title: .arrayThree, bools: $vm.bools)
.onChange(of: vm.bools){ _ in vm.getArray()}
}
Record {
ForEach(vm.contentArray, id: .self) { content material in
Textual content(content material.self)
}
}
}
.onAppear {vm.setButtons()}
.onAppear {vm.getArray()}
}
}
This is the code for the buttons
import SwiftUI
struct SortButton: View {
var title: Choose
@Binding var bools: [String : Bool]
var physique: some View {
Button {
func present(button: Choose) {
Choose.allCases.forEach { button in
bools[button.rawValue] = false
}
bools[button.rawValue] = true
}
} label: {
Textual content(title.rawValue)
}
}
}
enum Choose: String, CaseIterable {
case arrayOne = "arrayOne"
case arrayTwo = "arrayTwo"
case arrayThree = "arrayThree"
}
And at last the ViewModel for this instance.
import Basis
class ContentViewModel: ObservableObject {
@Printed var contentArray = [String]()
@Printed var bools = [String : Bool]()
non-public let arrayOne = ["One", "Two", "Three"]
non-public let arrayTwo = ["Four", "Five", "Six"]
non-public let arrayThree = ["Seven", "Eight", "Nine"]
func setButtons() {
Choose.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)
}
}
}
Hyperlink to instance mission on GitHub:
https://github.com/sans-connaissance/SOQ-BetterButtons
Thanks for having a look!!
[ad_2]
