ReactiveSwift简单示例
问题描述:
我读过documentation,通过他们精彩的游乐场示例,搜索了S.O.,并且达到了我的google-fu的范围,但是我不能在我的生活中围绕如何使用ReactiveSwift。ReactiveSwift简单示例
鉴于以下....
class SomeModel {
var mapType: MKMapType = .standard
var selectedAnnotation: MKAnnotation?
var annotations = [MKAnnotation]()
var enableRouteButton = false
// The rest of the implementation...
}
class SomeViewController: UIViewController {
let model: SomeModel
let mapView = MKMapView(frame: .zero) // It's position is set elsewhere
@IBOutlet var routeButton: UIBarButtonItem?
init(model: SomeModel) {
self.model = model
super.init(nibName: nil, bundle: nil)
}
// The rest of the implementation...
}
....我如何使用ReactiveSwift从SomeModel
初始化SomeViewController
的价值观,然后更新SomeViewController
每当SomeModel
变化值是多少?
我以前从来没有用过任何反应,但是我读的所有东西都让我相信这应该是可能的。 这让我发疯。
我意识到ReactiveSwift比本示例中要实现的要多得多,但如果有人可以请使用它来帮助我开始,我将不胜感激。我希望一旦我得到这部分,其余的只是“点击”。
答
首先,您需要在模型中使用MutableProperty
而不是普通类型。这样,您可以观察对它们的更改。
class Model {
let mapType = MutableProperty<MKMapType>(.standard)
let selectedAnnotation = MutableProperty<MKAnnotation?>(nil)
let annotations = MutableProperty<[MKAnnotation]>([])
let enableRouteButton = MutableProperty<Bool>(false)
}
在你的ViewController,然后你可以绑定这些观察那些无论多么有必要:
class SomeViewController: UIViewController {
let viewModel: Model
let mapView = MKMapView(frame: .zero) // It's position is set elsewhere
@IBOutlet var routeButton: UIBarButtonItem!
init(viewModel: Model) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
routeButton.reactive.isEnabled <~ viewModel.enableRouteButton
viewModel.mapType.producer.startWithValues { [weak self] mapType in
// Process new map type
}
// Rest of bindings
}
// The rest of the implementation...
}
注意MutableProperty
兼备,一个.signal
以及一个.signalProducer
。 如果您立即需要MutableProperty
的当前值(例如,用于初始设置),请使用.signalProducer
,它立即发送带有当前值的事件以及任何更改。
如果您只需要对将来的更改做出反应,请使用.signal
,它只会发送事件以便将来进行更改。
Reactive Cocoa 5.0 will add UIKit bindings您可以使用它将UI元素直接绑定到您的反应层,如在示例中使用routeButton
完成的那样。
刚刚听到的“点击”是我阅读你的答案后有意义的一切。谢谢你在这个例子中分解它,因为它使所有的区别! – forgot
很高兴我能帮到你 – MeXx