我是 RxSwift 的新手。 我在屏幕上有 3 个 UIControl。选择一个或所有控件应启用屏幕底部的“下一步”UIButton。
我不明白:
我的模特:
struct Model {
let isFirstButtonSelected: Bool
let isSecondButtonSelected: Bool
let isThirdButtonSelected: Bool
}
let model: Observable<Model>
我的视图是这样配置的:
func configure(_ model: Model) {
firstButton.isSelected = model.isFirstButtonSelected
secondButton.isSelected = model.isSecondButtonSelected
thirdButton.isSelected = model.isThirdButtonSelected
}
您没有说明是什么原因导致按钮首先被选中。为了实施解决方案,需要知道这一点。
对于下面的内容,我假设点击按钮将切换其选定状态。以下代码将跟踪每个按钮的选定状态,并将创建
Observable<Model>
.
注释在解释每个步骤的代码中。
func example(button: UIButton, button1: UIButton, button2: UIButton, disposeBag: DisposeBag) -> Observable<Model> {
// Put the buttons in an array to reduce code duplication.
let buttons = [button, button1, button2]
// Create three `Observable<Bool>`s that track the selected status of each button based on how many times it was tapped. The state is toggled from false to true then back to false...
let selecteds = buttons.map { button in
button.rx.tap
.scan(false) { state, _ in !state } // toggle the state for each tap
.startWith(false) // start with the false state
.share(replay: 1) // save the most recent state and replay it for each subscriber.
}
// update the selected status of the buttons based on the above Observables. This isn't strictly necessary for the solution.
for (button, selected) in zip(buttons, selecteds) {
selected
.bind(to: button.rx.isSelected)
.disposed(by: disposeBag)
}
// combine the three selected statuses into an Array of Bools. Create a new Model every time one of the three statuses changes.
return Observable.combineLatest(selecteds) { Model(isFirstButtonSelected: $0[0], isSecondButtonSelected: $0[1], isThirdButtonSelected: $0[2]) }
}