WWDC 2019 Data Flow Through Swif

2019-07-22  本文已影响0人  Jerrydu96

You don't need to ViewController anymore
Toggle、TextField、Slider都已经定义了Binding来绑定数据

introducing Combine and Advances in Foundation
Combine in Practice
//All In WWDC 2019

BindableObject Protocol

External
Reference type
Great for model you already have

class PodcastPlayerStore : BindableObject {
    //Publisher
    var didChange = PassthroughSubject<Void, Never>()
    //...
    func advance() {
        currentEpisode = nextEpisode
        currentTime = 0.0
        // Notify subscribers that the player changed
        didChange.send()
    }
} 

使用例子

Creating Dependencies on BindableObject

Pass directly with @ObjectBinding
Automatic dependency tracking

struct MyView : View {
    @ObjectBinding var model: MyModelObject
    ...
}
//创建对象,绑定model
MyView(model: modelInstance)
struct PlayerView : View {
    @EnvironmentObject var player: PodcastPlayerStore

    var body: some View {
        VStack {
            Text(player.currentEpisode.title)
                .foregroundColor(isPlaying ? .white : .gray)
            Text(player.currentEpisode.showTitle)
                .font(.caption).foregroundColor(.gray)
  
            PlayButton(isPlaying: $player.isPlaying)

            Text("\(player.currentTime, formatter: playheadTimeFormatter)")
        }
    }
}

Environment

Data applicable to an entire hierarchy
Convenience for indirection
Accent color, right-to-left, and more

Building Reusable Components

Read-only: Swift property, Environment
Read-write:@Binding
Prefer immutable access

@Binding

First class reference to data
*@Binding read and write a value without owning it
Great for reusability
Use $ to derive from source

Using State Effectively

Limit use if possible
Use derived Binding or value
Prefer BindableObject for persistence
Example: Button highlighting

上一篇下一篇

猜你喜欢

热点阅读