for*_*got 11 reactive-cocoa swift3
我已经阅读了文档,通过他们精彩的Playground示例,搜索了SO,并达到了我的google-fu的范围,但我不能为我的生活包围我如何使用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...
}
Run Code Online (Sandbox Code Playgroud)
....如何使用ReactiveSwift初始化SomeViewController值SomeModel,然后SomeViewController在SomeModel更改值时更新?
我以前从未使用过反应,但我读过的所有内容都让我相信这应该是可能的.这让我发疯了.
我意识到ReactiveSwift还有比我在这个例子中想要实现的更多,但如果有人可以用它来帮助我开始,我将非常感激.我希望一旦我得到这个部分,剩下的就是"点击".
MeX*_*eXx 19
首先,您需要MutableProperty在模型中使用而不是普通类型.这样,您可以观察对它们的更改.
class Model {
let mapType = MutableProperty<MKMapType>(.standard)
let selectedAnnotation = MutableProperty<MKAnnotation?>(nil)
let annotations = MutableProperty<[MKAnnotation]>([])
let enableRouteButton = MutableProperty<Bool>(false)
}
Run Code Online (Sandbox Code Playgroud)
在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...
}
Run Code Online (Sandbox Code Playgroud)
注意,MutableProperty既有a又有.signala .signalProducer.如果您立即需要a的当前值MutableProperty(例如,用于初始设置),请使用.signalProducer该值立即发送具有当前值的事件以及任何更改.
如果您只需要对将来的更改做出反应,请使用.signal该更改仅发送事件以供将来更改.
Reactive Cocoa 5.0将添加UIKit绑定,您可以使用它直接将UI元素绑定到您的反应层,就像routeButton示例中所做的那样.
| 归档时间: |
|
| 查看次数: |
2631 次 |
| 最近记录: |