使用ReactiveCocoa 4和NSButton计算bean

时间:2015-11-29 15:29:40

标签: ios swift reactive-cocoa reactive-cocoa-3

我有以下内容:

  • 两个有趣的课程:ViewControllerViewModel
  • nsButtonMorePlease:NSButton view
  • 中的按钮ViewController
  • nsTextView:NSTextView中的文本框view以及

我想要以下行为:

  • 启动程序时,“计数”从0开始,显示在文本框nsTextView
  • 当您按下按钮nsButtonMorePlease时,计数会增加1,更新的计数会反映在nsTextView

我想确保:

  • 我使用ReactiveCocoa 4(这就是点数)
  • 模型类包含从numberOfBeans: MutableProperty<Int>
  • 开始的0
  • 设计纯粹是功能性的或接近它 - 即(如果我理解术语),链中的每个链接都将鼠标点击事件映射到MutableProperty numberOfBeans以响应它在文本视图中,都没有副作用。

这就是我所拥有的。公平警告:我认为这并不接近工作或编译。但我觉得我可能想要使用combineLatestcollectreduce之一等等。只是失去了具体做什么。我觉得这样会让事情变得非常困难。

class CandyViewModel {

    private let racPropertyBeansCount: MutableProperty<Int> = MutableProperty<Int>(0)

    lazy var racActionIncrementBeansCount: Action<AnyObject?, Int, NoError> = {
        return Action { _ in SignalProducer<Int, NoError>(value: 1)
        }
    }()

    var racCocoaIncrementBeansAction: CocoaAction

    init() {
        racCocoaIncrementBeansAction = CocoaAction.init(racActionIncrementBeansCount, input: "")
        // ???
        var sig = racPropertyBeansCount.producer.combineLatestWith(racActionIncrementBeansCount.)
    }

}

class CandyView: NSViewController {

    @IBOutlet private var guiButtonMoreCandy: NSButton!
    @IBOutlet private var guiTextViewCandyCt: NSTextView!



}

1 个答案:

答案 0 :(得分:1)

class CandyViewModel {

    let racPropertyBeansCount = MutableProperty<Int>(0)

    let racActionIncrementBeansCount = Action<(), Int, NoError>{ _ in SignalProducer(value: 1) }

    init() {

        // reduce the value from the action to the mutableproperty
        racPropertyBeansCount <~ racActionIncrementBeansCount.values.reduce(racPropertyBeansCount.value) { $0 + $1 }

    }

}

class CandyView: NSViewController {

    // define outlets

    let viewModel = CandyViewModel()


    func bindObservers() {

        // bind the Action to the button
        guiButtonMoreCandy.addTarget(viewModel.racActionIncrementBeansCount.unsafeCocoaAction, action: CocoaAction.selector, forControlEvents: .TouchUpInside)

        // observe the producer of the mutableproperty
        viewModel.racPropertyBeansCount.producer.startWithNext {
            self.guiTextViewCandyCt.text = "\($0)"
        }

    }

}