如何使用ReactiveCocoa 3实现基本的UITextField输入+ UIButton操作场景?

asl*_*nci 8 mvvm ios reactive-cocoa swift reactive-cocoa-3

我同时是一个Swift和ReactiveCocoa noob.使用MVVM和Reactive Cocoa v3.0-beta.4框架,我想实现此设置,以了解新RAC 3框架的基础知识.

我有一个文本字段,我希望文本输入包含超过3个字母,以进行验证.如果文本通过验证,则应启用下面的按钮.当按钮收到触地事件时,我想使用视图模型的属性触发操作.

由于目前关于RAC 3.0 beta的资源很少,我通过阅读框架的Github repo上的QA来实现以下内容.到目前为止,这是我能想到的:

ViewModel.swift

class ViewModel {

    var text = MutableProperty<String>("")
    let action: Action<String, Bool, NoError>
    let validatedTextProducer: SignalProducer<AnyObject?, NoError>

    init() {
        let validation: Signal<String, NoError> -> Signal<AnyObject?, NoError> = map ({
            string in
            return (count(string) > 3) as AnyObject?
        })

        validatedTextProducer = text.producer.lift(validation)

        //Dummy action for now. Will make a network request using the text property in the real app. 
        action = Action { _ in
            return SignalProducer { sink, disposable in
                sendNext(sink, true)
                sendCompleted(sink)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ViewController.swift

class ViewController: UIViewController {

    private lazy var txtField: UITextField = {
        return createTextFieldAsSubviewOfView(self.view)
    }()

    private lazy var button: UIButton = {
        return createButtonAsSubviewOfView(self.view)
    }()

    private lazy var buttonEnabled: DynamicProperty = {
       return DynamicProperty(object: self.button, keyPath: "enabled")
    }()

    private let viewModel = ViewModel()
    private var cocoaAction: CocoaAction?

    override func viewDidLoad() {
        super.viewDidLoad()
        view.setNeedsUpdateConstraints()

        bindSignals()
    }

    func bindSignals() {
        viewModel.text <~ textSignal(txtField)
        buttonEnabled <~ viewModel.validatedTextProducer

        cocoaAction = CocoaAction(viewModel.action, input:"Actually I don't need any input.")
        button.addTarget(cocoaAction, action: CocoaAction.selector, forControlEvents: UIControlEvents.TouchDown)

        viewModel.action.values.observe(next: {value in
            println("view model action result \(value)")
        })
    }

    override func updateViewConstraints() {
        super.updateViewConstraints()

        //Some autolayout code here
    }
}
Run Code Online (Sandbox Code Playgroud)

RACUtilities.swift

func textSignal(textField: UITextField) -> SignalProducer<String, NoError> {
    return textField.rac_textSignal().toSignalProducer()
        |> map { $0! as! String }
        |> catch {_ in SignalProducer(value: "") }
}
Run Code Online (Sandbox Code Playgroud)

使用此设置,当视图模型的文本超过3个字符时,该按钮将启用.当用户点击按钮时,视图模型的操作会运行,我可以将返回值设置为true.到现在为止还挺好.

我的问题是:在视图模型的操作中,我想使用其存储的文本属性并更新代码以使用它来发出网络请求.所以,我不需要视图控制器端的输入.我怎么能要求我的Action属性输入?

Jak*_*ano 4

来自ReactiveCocoa/CHANGELOG.md

操作必须指示它接受的输入类型、它产生的输出类型以及可能发生的错误类型(如果有)。

所以目前没有办法在Action没有输入的情况下定义 an 。

AnyObject?我想您可以通过使用方便的初始化程序进行创建和创建来声明您不关心输入CocoaAction

cocoaAction = CocoaAction(viewModel.action)
Run Code Online (Sandbox Code Playgroud)

补充说明

  • 我不喜欢用forAnyObject?代替。我想您更喜欢它,因为绑定到属性需要. 不过,我宁愿将其投射到那里,而不是牺牲视图模型的类型清晰度(请参见下面的示例)。BoolvalidatedTextProducerbuttonEnabledAnyObject?

  • 您可能希望限制Action视图模型级别以及 UI 上的执行,例如:

    class ViewModel {
    
        var text = MutableProperty<String>("")
        let action: Action<AnyObject?, Bool, NoError>
    
        // if you want to provide outside access to the property
        var textValid: PropertyOf<Bool> {
            return PropertyOf(_textValid)
        }
    
        private let _textValid = MutableProperty(false)
    
        init() {
            let validation: Signal<String, NoError> -> Signal<Bool, NoError> = map { string in
                return count(string) > 3
            }
    
            _textValid <~ text.producer |> validation
    
            action = Action(enabledIf:_textValid) { _ in
                //...
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

    并绑定到buttonEnabled

    func bindSignals() {
        buttonEnabled <~ viewModel.action.enabled.producer |> map { $0 as AnyObject }
        //...
    }
    
    Run Code Online (Sandbox Code Playgroud)