2016-09-28 27 views
1

我試圖在UISwitch上綁定ActionReactiveSwift - 將`Action`綁定到`UIControl`

我曾嘗試使用下面的代碼

action = Action<UISwitch, Bool, NoError> { (input: UISwitch) -> SignalProducer<Bool, NoError> in 
     return SignalProducer{ (observer, disposable) in 
      observer.send(value: input.isOn) 
      observer.sendCompleted() 
     } 
    } 

創建的行動,但我有它連接到UISwitch麻煩。

有人可以幫忙嗎?

回答

1

還有另一類CocoaAction用來包裹Action S和它們連接到UIControl(現在的中ReactiveCocoa,而不是在覈心ReactiveSwift,因此,如果您正在使用RAC 5,你將不得不同時導入)

var switch: UISwitch! 

//switch.addTarget() does not retain the target, so if we do not 
//keep a strong reference here the cocoaAction will be deallocated 
//at the end of viewDidLoad() and you will get unrecognized selector 
//errors when the switch tries to execute the action 
var switchCocoaAction: CocoaAction! 

override func viewDidLoad() { 
    let action = Action<UISwitch, Bool, NoError> { (input: UISwitch) -> SignalProducer<Bool, NoError> in 
    return SignalProducer { (observer, disposable) in 
     observer.send(value: input.isOn) 
     observer.sendCompleted() 
    } 
    } 

    //unsafe because it will cast anyObject as! UISwitch 
    self.switchCocoaAction = action.unsafeCocoaAction 

    switch.addTarget(switchCocoaAction, 
    action: CocoaAction.selector, 
    forControlEvents: .ValueChanged 
) 
} 

但是,如果你想要的是發射switch.isOn值時,它改變的信號,就可以實現這個目標更容易使用內建rac_signalForControlEvents

func switchSignal() -> SignalProducer<Bool, NoError> { 
    switch.rac_signalForControlEvents(.ValueChanged) //returns legacy RACsignal 
    .toSignalProducer() //legacy RACSignal -> swift SignalProducer 
    .flatMapError { _ in .empty } //NSError -> NoError, errors not possible here, so ignore them 
    .map { ($0 as! UISwitch).isOn } 
} 
相關問題