如何将UIButton.isSelectable与RXSwift绑定

时间:2017-08-11 09:35:17

标签: ios swift uibutton rx-swift

// This button has different images with for selection and no selection which I configured in storyboard different images for two states.

@IBOutlet weak var selectedRestarunt: UIButton!
    // I am binding isSelected state like this which is working when user taps on button.
    selectedRestarunt.rx.tap.scan(false) { lastState, _ in
        return !lastState
    }

现在我有一个案例我手动标记isSelected而没有点击。

selectedRestarunt.isSelected = false/true

这不应该触发现有的映射。 这应该以某种方式映射,以便我需要基于isSelected状态的某些操作。 谁能解释我怎样才能实现这个目标?

1 个答案:

答案 0 :(得分:0)

您可以使用类似RxFeedback的架构:

...
let isSelected = PublishSubject<Bool>()

enum Event {
    case setIsSelected(Bool)
    case toggle
}

override func viewDidLoad() {
    super.viewDidLoad()

    Observable.merge(
        isSelected.map { Event.setIsSelected($0) },
        selectedRestarunt.rx.tap.map { _ in Event.toggle }
    ).scan(false) { lastState, event in
        switch event {
        case .setIsSelected(let selected):
            return selected
        case .toggle:
            return !lastState
        }
    }.bind(to: selectedRestarunt.rx.isSelected)
    .disposed(by: disposeBag)



    isSelected.onNext(true) // Mark isSelected manually without tap.
}
...

使用Event枚举来描述状态更改,然后使用scan运算符应用更改。