SwiftUI ObservedObject如何轉換爲Binding (教程含源碼) 實戰需求 基礎知識 實戰代碼 加入我們一起學習SwiftUI

實戰需求

SwiftUI ObservedObject如何轉換爲Binding


基礎知識

ObservableObject

具有發佈者的一種對象,該對象在更改對象之前發出。

protocol ObservableObject : AnyObject

總覽
默認情況下,合成器將在其任何屬性更改之前發出更改後的值的發佈程序。


class Contact: ObservableObject {
    @Published var name: String
    @Published var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    func haveBirthday() -> Int {
        age += 1
        return age
    }
}

let john = Contact(name: "John Appleseed", age: 24)
cancellable = john.objectWillChange
    .sink { _ in
        print("\(john.age) will change")
}
print(john.haveBirthday())
// Prints "24 will change"
// Prints "25"

實戰代碼

struct ContentView: View {
    @StateObject var dataModel = DataModel()

    var body: some View {
        DataView(dataModel: dataModel)
    }
}

struct DataView: View {
    @ObservedObject var dataModel: DataModel

    var body: some View {
        Text(dataModel.data)
            .padding()
    }
}

加入我們一起學習SwiftUI

QQ:3365059189
SwiftUI技術交流QQ羣:518696470

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章