还有另一个CocoaAction
用于包装Action
s 并将它们连接到UIControl
s 的类(现在在ReactiveCocoa
而不是在 core 中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 }
}