1

我正在尝试将一个绑定Action到一个UISwitch.

我使用以下代码创建了动作

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

但我无法将它连接到UISwitch.

有人可以帮忙吗?

4

1 回答 1

1

还有另一个CocoaAction用于包装Actions 并将它们连接到UIControls 的类(现在在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 }
}
于 2016-10-14T19:39:45.207 回答