SwiftUI-尽管使用@Published和@ObservedObject

时间:2020-09-19 15:27:05

标签: ios swift mobile foreach swiftui

使用SwiftUI更新应用的主视图时遇到问题。

所以,我有一个Dog结构( Dog.swift ):

struct Dog: Identifiable {

var id = UUID()
var name: String
var race: String
var age: Int
var gender: String
var sterile: Bool
var pictureURL: String
var location: String
var dogFriendly: Bool
var catFriendly: Bool
var childFriendly: Bool
var needsGarden: Bool
var isClean: Bool
}

我的目标是在 AddView.swift 中按下此按钮:

@ObservedObject var viewModel = AddViewModel()
 ************** LONG UI CODE *******************
.navigationBarItems(trailing:
                    Button("Publish") {
                        viewModel.dogs.append(Dog(name: self.name, race: races[selectedRace], age: self.age, gender: genders[selectedGender], sterile: self.isSterile, pictureURL: "", location: "", dogFriendly: self.isDogFriendly, catFriendly: self.isCatFriendly, childFriendly: self.isChildFriendly, needsGarden: self.needsGarden, isClean: self.isClean))
                        print(viewModel.dogs)
                })

将狗添加到 AddViewModel.swift 中的Dog数组中:

class AddViewModel: ObservableObject {

@Published var dogs: [Dog] = []
}

,然后在CardView中显示信息:

struct CardView: View {

//MARK: - Properties

@State var dog: Dog

//MARK: - View

var body: some View {
******* LONG UI CODE ********
}

并在HomeView中显示那些CardView:

struct HomeView: View {

@ObservedObject var viewModel = AddViewModel()


var body: some View {
    ScrollView {
        VStack {
            ForEach(viewModel.dogs) { dog in
                CardView(dog: dog) // this doesn't work
                Text(dog.name) // this doesn't work neither
            }
        }
    }
}

}

有人可以帮我解决这个问题,并给我一些建议吗?

感谢您的慷慨帮助!

2 个答案:

答案 0 :(得分:0)

将@State更改为@Bindig将对其进行修复。

CardView:

struct CardView: View {

//MARK: - Properties

@Binding var dog: Dog

//MARK: - View

var body: some View {
******* LONG UI CODE ********
}

答案 1 :(得分:0)

我认为您想在console.log(JSON.stringify(request.body)); 内附加Array的{​​{1}}并在Dog内显示更新的数据。因此,您只是在每个视图中分别声明了AddView的实例。视图中的两个实例不会相互观察。为了解决这个问题,我更喜欢使用HomeView模式。这是我的示例代码。

AddViewModel