【问题标题】:How to create RxSwift sequence based on selected UIButtons?如何根据选定的 UIButtons 创建 RxSwift 序列?
【发布时间】:2023-02-23 07:14:55
【问题描述】:

我是 RxSwift 的新手。 我在屏幕上有 3 个 UIControl。选择一个或所有控件应启用屏幕底部的“下一步”UIButton。

我不明白如何:

  1. 如何根据 UIControl 的 isSelected 属性创建点击序列?
  2. 如何在选择这些按钮后更新可观察模型?鉴于模型是不可变的。
  3. 如何正确存储/保存选定的值?

    我的模型:

    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
    }
    

【问题讨论】:

  • 按钮的 rx.isSelected 属性是一个 Binder,它是一种 Observer。你无法观察观察者;你只能观察一个可观察的。因此,您的代码中的某些内容导致按钮被选中。那是什么?

标签: rx-swift


【解决方案1】:

您没有指定导致按钮首先被选中的原因。为了实施解决方案,需要知道这一点。

对于下面的内容,我将假设点击按钮将切换其选定状态。以下代码将跟踪每个按钮的选定状态并创建Observable&lt;Model&gt;

注释在解释每个步骤的代码中。

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]) }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2019-02-13
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    相关资源
    最近更新 更多