ReactiveSwift - 更新MutableProperty的价值?

时间:2016-12-14 05:03:03

标签: swift3 reactive-cocoa

作为this问题的后续内容,收到this fantastic answer,并使用以下示例...

class Model {
    let mapType = MutableProperty<MKMapType>(.standard)
}

class SomeViewController: UIViewController {

    let viewModel: Model
    var mapView: MKMapView!

    init(viewModel: Model) {
        self.viewModel = viewModel
        super.init(nibName: nil, bundle: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView = // Create the map view
        viewModel.mapType.producer.startWithValues { [weak self] mapType in
            self?.mapView.mapType = mapType
        }
        // Rest of bindings
    }
    // The rest of the implementation...
}

class SomeOtherViewController: UIViewController {

    let viewModel: Model
    var segmentedControl: UISegmentedControl!

    init(viewModel: Model) {
        self.viewModel = viewModel
        super.init(nibName: nil, bundle: nil)
        // Pretend we've setup the segmentedControl, and set its action to `updateMap(sender:)`...
        // The rest of the initialization...
    }

    func updateMap(sender: UISegmentedControl) {
        let newMapType =...
        self.viewModel.mapType = newMapType // How do I update this value?
    }
    // The rest of the implementation...
}

如何更新Model.mapType的值,并将其更改发送给任何观察者(例如示例中的SomeViewController)?

1 个答案:

答案 0 :(得分:5)

您只需设置其value属性,这将触发自动发送给观察者的更改。

self.viewModel.mapType.value = newMapType