如您在official tutorial project中所看到的,在@EnvironmentObject
之前放置了这个奇怪的var
。这是什么意思?
struct LandmarkDetail: View {
@EnvironmentObject var userData: UserData
var landmark: Landmark
var landmarkIndex: Int {
userData.landmarks.firstIndex(where: { $0.id == landmark.id })!
}
// ...
}
最佳答案
例如,出于网络目的。您有一个符合BindableObject
(测试版5:ObservableObject
)的类,并通过PassthroughSubject
(测试版5:@Published
)发送数据。
例如这种情况:
SwiftUI(1.0)
struct Course: Decodable {
let name: String
}
class NetworkManager: ObservableObject {
@Published var courses = [Course]()
func getAllCourses() {
guard let url = URL(string: "https://api.letsbuildthatapp.com/jsondecodable/courses") else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
do {
let courses = try JSONDecoder().decode([Course].self, from: data!)
DispatchQueue.main.async {
self.courses = courses
}
} catch {
print("Failed To decode: ", error)
}
}.resume() // VERY IMPORTANT! As the request won't run
}
}
struct ContentView : View {
@ObservedObject var networkManager: NetworkManager = NetworkManager()
// Or this
// @EnvironmentObject var networkManager: NetworkManager // Don't forget to instaniate it with .environmentObject()
var body: some View {
VStack {
Button(action: {
self.networkManager.getAllCourses()
}, label: {
Text("Get All Courses")
})
List(networkManager.courses, id: \.name) {
Text($0.name)
}
}
}
}
Beta
struct Course: Decodable {
let name: String
}
class NetworkManager: BindableObject {
let didChange = PassthroughSubject<NetworkManager, Never>()
var courses = [Course]() {
didSet {
didChange.send(self)
}
}
func getAllCourses() {
guard let url = URL(string: "https://api.letsbuildthatapp.com/jsondecodable/courses") else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
do {
let courses = try JSONDecoder().decode([Course].self, from: data!)
DispatchQueue.main.async {
self.courses = courses
}
} catch {
print("Failed To decode: ", error)
}
}.resume() // VERY IMPORTANT! As the request won't run
}
}
struct ContentView : View {
@EnvironmentObject var networkManager: NetworkManager
var body: some View {
VStack {
Button(action: {
self.networkManager.getAllCourses()
}, label: {
Text("Get All Courses")
})
List(networkManager.courses.identified(by: \.name)) {
Text($0.name)
}
}
}
}
关于ios - SwiftUI中的 `@EnvironmentObject`属性是什么意思?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56437035/