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

时间:2015-05-08 19:30:32

标签: ios swift mvvm reactive-cocoa 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)
            }
        }
    }
}

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
    }
}

RACUtilities.swift

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

使用此设置,当视图模型的文本超过3个字符时,该按钮将启用。当用户点击按钮时,视图模型的操作会运行,我可以将返回值设置为true。到目前为止一切都很好。

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

2 个答案:

答案 0 :(得分:4)

来自ReactiveCocoa/CHANGELOG.md

  

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

因此,目前无法在没有输入的情况下定义Action

我想你可以通过使用方便初始化来AnyObject?并创建CocoaAction来声明你不关心输入:

cocoaAction = CocoaAction(viewModel.action)

补充说明

  • 我不喜欢AnyObject?而不是Bool使用validatedTextProducer。我想你更喜欢它,因为绑定到buttonEnabled属性需要AnyObject?。我宁愿把它扔在那里,而不是牺牲我的视图模型的类型清晰度(见下面的例子)。

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

    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
                //...
            }
        }
    }
    

    绑定到buttonEnabled

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

答案 1 :(得分:2)

如果你看一下关于ReactiveCocoa 3的Colin Eberhardt blog post,就可以解决这个问题。

基本上因为它仍处于测试阶段,UIView上没有任何扩展程序可以使这些属性与RAC3一起使用,但您可以轻松添加它们。我建议您添加UIKit+RAC3.swift扩展程序并根据需要添加它们:

import UIKit
import ReactiveCocoa

struct AssociationKey {
    static var hidden: UInt8 = 1
    static var alpha: UInt8 = 2
    static var text: UInt8 = 3
    static var enabled: UInt8 = 4
}

func lazyAssociatedProperty<T: AnyObject>(host: AnyObject,
    key: UnsafePointer<Void>, factory: ()->T) -> T {
        var associatedProperty = objc_getAssociatedObject(host, key) as? T

        if associatedProperty == nil {
            associatedProperty = factory()
            objc_setAssociatedObject(host, key, associatedProperty,
                UInt(OBJC_ASSOCIATION_RETAIN))
        }
        return associatedProperty!
}

func lazyMutableProperty<T>(host: AnyObject, key: UnsafePointer<Void>,
    setter: T -> (), getter: () -> T) -> MutableProperty<T> {
        return lazyAssociatedProperty(host, key) {
            var property = MutableProperty<T>(getter())
            property.producer
                .start(next: {
                    newValue in
                    setter(newValue)
                })
            return property
        }
}

extension UIView {
    public var rac_alpha: MutableProperty<CGFloat> {
        return lazyMutableProperty(self, &AssociationKey.alpha, { self.alpha = $0 }, { self.alpha  })
    }

    public var rac_hidden: MutableProperty<Bool> {
        return lazyMutableProperty(self, &AssociationKey.hidden, { self.hidden = $0 }, { self.hidden  })
    }
}

extension UIBarItem {
    public var rac_enabled: MutableProperty<Bool> {
        return lazyMutableProperty(self, &AssociationKey.enabled, { self.enabled = $0 }, { self.enabled  })
    }
}

这样你只需用(例如)代替RAC = RACObserve逻辑:

var date = MutableProperty<NSDate?>(nil)
var time = MutableProperty<Int?>(nil)

let doneItem = UIBarButtonItem()
doneItem.rac_enabled <~ date.producer
        |> combineLatestWith(time.producer)
        |> map { return $0.0 != nil && $0.1 != nil }

这一切都取自他的博客文章,这个文章比这个答案更具描述性。我强烈建议任何有兴趣使用RAC 3的人阅读他惊人的帖子和教程: