gpt4 book ai didi

swift3 - ReactiveSwift 简单示例

转载 作者:行者123 更新时间:2023-12-03 18:07:30 27 4
gpt4 key购买 nike

我已阅读 documentation ,浏览了他们精彩的 Playground 示例,搜索了 S.O.,并达到了我的 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...
}

....如何使用 ReactiveSwift 初始化 SomeViewController使用 SomeModel 中的值,然后更新 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 中,您可以绑定(bind)它们并观察那些必要的:
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它立即发送带有当前值以及任何更改的事件。

如果您只需要对 future 的变化使用react,请使用 .signal这只会发送事件以供将来更改。

Reactive Cocoa 5.0 will add UIKit bindings您可以使用它直接将 UI 元素绑定(bind)到您的 react 层,就像使用 routeButton 完成的一样在示例中。

关于swift3 - ReactiveSwift 简单示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40836748/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com