美文网首页
WWDC 2019 Data Flow Through Swif

WWDC 2019 Data Flow Through Swif

作者: Jerrydu96 | 来源:发表于2019-07-22 00:36 被阅读0次

    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

    相关文章

      网友评论

          本文标题:WWDC 2019 Data Flow Through Swif

          本文链接:https://www.haomeiwen.com/subject/flsblctx.html