[英]Get changes on button tapped using Combine and SwiftUI
Trying to change isValid
after the user have chose from the Menu
the right position.在用户从Menu
选择正确的位置后尝试更改isValid
。
It seems to work if I first choose a position and then typing the email and name at the textfields but not the other side.如果我首先选择一个职位,然后在文本字段而不是另一侧输入电子邮件和姓名,这似乎有效。
I want to enable the Button
when he chose position and fulfilled the other textfields.我想在他选择位置并完成其他文本字段时启用Button
。
class EmployeeModel: ObservableObject{
@Published var employee: Employee
@Published var isValid = false
private var cancellables = Set<AnyCancellable>()
init(employee: Employee = Employee(uid: "", affiliate: 0, employeeID: 1, email: "", name: "", shiftsConstIsApplied: false, position: nil, shiftConsts: nil, pushId: "")){
self.employee = employee
self.$employee
.debounce(for: 0.5, scheduler: RunLoop.main)
.map({!$0.name.isEmpty && !$0.email.isEmpty && $0.position != nil})
.sink{ input in
print(input)
self.isValid = input
}
.store(in: &cancellables)
}
}
The view:风景:
@State private var position: Positions?
@StateObject var employeeModel = EmployeeModel()
Menu(LocalizedStringKey(self.$position.wrappedValue?.rawValue ?? "Choose position")) {
ForEach(Positions.employeeTypes, id:\.self){ p in
Button(LocalizedStringKey(p)){
let positionSelected = Positions(rawValue: p)
self.position = positionSelected
self.employeeModel.employee.position = positionSelected
}
}
}
Button("Confirm"){
//do something
}
.disabled(!self.employeeModel.isValid)
Model Employee as ObservableObject:将员工建模为 ObservableObject:
@Published var uid: String?
@Published var email: String
@Published var name: String
@Published var affiliate: Int?
@Published var employeeId: Int?
@Published var shiftsConstIsApplied: Bool? = true
@Published var position: Positions?
@Published var shiftConsts: [ShiftConst]?
If I correctly understood your code try the following (not tested!)如果我正确理解您的代码,请尝试以下操作(未测试!)
init(employee: Employee = Employee(uid: "", affiliate: 0, employeeID: 1, email: "", name: "", shiftsConstIsApplied: false, position: nil, shiftConsts: nil, pushId: "")){
self.employee = employee
self.employee.objectWillChange // << here !!
.debounce(for: 0.5, scheduler: RunLoop.main)
, you don't change employee itself (because it is reference type), but just its internal property, so you need to subscribe to its internal publisher. ,你不会改变employee本身(因为它是引用类型),而只是改变它的内部属性,所以你需要订阅它的内部发布者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.