2016-11-28 154 views
9

我讀過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比本示例中要實現的要多得多,但如果有人可以請使用它來幫助我開始,我將不勝感激。我希望一旦我得到這部分,其餘的只是「點擊」。

回答

17

首先,您需要在模型中使用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完成的那樣。

+2

剛剛聽到的「點擊」是我閱讀你的答案後有意義的一切。謝謝你在這個例子中分解它,因爲它使所有的區別! – forgot

+0

很高興我能幫到你 – MeXx