Hi everyone,
I want to perform the tutorial from video WWDC19 - 204. Here is an example of building the "Rooms" application. At 42 minutes, the author of the video, Jacob Xiao, shows how to add a new room. But when I try to repeat it, nothing happens. The new room is not added.
My code and code of Jacob Xiao are the same.
import SwiftUI
struct ContentView: View {
@ObservedObject var store = RoomStore()
// Instead of //var rooms: [Room] = []
// @ObservedObject is instead of @ObjectBinding
var body: some View {
NavigationView {
List {
Button(action: addRoom) {
Text("Add Room")
}
ForEach(store.rooms) { room in
RoomCell(room: room)
}
}
.navigationBarTitle(Text("Rooms"))
}
}
func addRoom() {
store.rooms.append(Room(name: "Hall 2", capacity: 2000))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(store: RoomStore(rooms: testData))
}
}
struct RoomCell: View {
var room: Room
var body: some View {
NavigationLink(destination: RoomDetail(room: room)) {
Image(room.thumbnailName)
.cornerRadius(8)
VStack(alignment: .leading) {
Text(room.name)
Text("\(room.capacity) people")
.font(.subheadline)
.foregroundColor(.secondary)
}
}
}
}
My project has also an image named "Hall 2".
What could be the reason that a new room is not being added? Any ideas, please.
Thanks for showing your code.
Unfortunately, the session video was made while SwiftUI was in beta, and you need to make the code updated in many, many points.
And BindableObject
having didChange
does not work in the released version of SwiftUI.
Please try this:
class RoomStore: ObservableObject { // Instead of BindableObject
@Published var rooms: [Room] //Use `@Published` here, no need to use `didChange`
init(rooms: [Room] = []) {
self.rooms = rooms
}
}
There are many good tutorials and sample codes written for the released version of SwiftUI. You should better find a good one unless you want to study how the beta version of SwiftUI was.