【问题标题】:Counting beans with ReactiveCocoa 4 and an NSButton使用 ReactiveCocoa 4 和 NSButton 计算 bean
【发布时间】:2016-03-03 06:06:14
【问题描述】:

我有以下几点:

  • 两个有趣的类:ViewControllerViewModel
  • ViewControllerview 中的一个按钮nsButtonMorePlease:NSButton
  • view 中还有一个文本框 nsTextView:NSTextView

我想要以下行为:

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

我想确保:

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

这就是我所拥有的。公平警告:我相信这并不接近工作或编译。但我确实觉得也许我想使用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!



}

【问题讨论】:

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


    【解决方案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)"
            }
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-23
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多