2017-08-11 207 views
0
// 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沒有水龍頭。我該如何綁定UIButton.isSelectable與RXSwift

selectedRestarunt.isSelected = false/true 

這應該不會觸發現有映射。 這應該以某種方式映射,以便我需要根據isSelected狀態進行一些操作。 有人可以解釋我怎麼能做到這一點?

+0

我想你應該爲'isSelected'屬性編寫自己的包裝器。參見:https://github.com/ReactiveX/RxSwift/blob/master/RxCocoa/iOS/UIButton%2BRx.swift –

回答

0

採用可變此:

SelectedState.value將包含你的狀態

let selectedState = Variable(true) 
_ = selectedState.asObservable().bindTo(selectedRestarunt.rx.isSelected) 
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運算符應用更改。