2016-09-28 2 views
1

ActionUISwitch에 바인딩하려고합니다.ReactiveSwift -`UIControl`에`Action`을 바인딩합니다.

다음 코드

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

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 
) 
} 
(당신은 RAC (5)를 사용하는 경우 모두를 가져올 것이다, 그래서 ReactiveCocoa에서가 아니라 핵심 ReactiveSwift 지금) Action의 포장 및 UIControl들에 연결하는 데 사용되는 다른 클래스 CocoaAction있다 원하는 모두가 변경 될 때마다 값 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 } 
} 
을 사용하여 훨씬 더 쉽게 달성 할