我使用的是经典数组:[struct]模型如下:
struct ContentView: View {
@State var showNewCardView = false
var MirleftCards: [mirleftCard] = [
mirleftCard(image: Image("beach"), title: "The Beach", description: "The amazing view of the Grande Plage"),
mirleftCard(image: Image("sea"), title: "The Sea", description: "The amazing view of the sea"),
]
var body: some View {
NavigationView{
ScrollView {
ForEach(MirleftCards, id: \.id) { card in
CardView(card_image: card.image, card_title: card.title, card_description: card.description)
}
}
}
}
原始结构如下:
struct mirleftCards: Identifiable {
var id = UUID()
var image: Image
var title: String
var description: String
}
我有一个.sheet编辑器,可让您上传图片并添加标题和说明:
class NewCardData: ObservableObject {
@Published var title = ""
@Published var description = ""
}
struct NewCardView: View {
@ObservedObject var newCardData = NewCardData()
@State var image:UIImage?
var body: some View {
if image != nil {
Image(uiImage: image!)
.resizable()
.scaledToFit()
.clipShape(RoundedRectangle(cornerRadius: 20))
.overlay(TextField("Title", text: $newCardData.title)
.overlay(TextField("Description", text: $newCardData.description)
}
}
}
我的问题是,当用户选择图像并输入标题和描述时,如何将这些数据自动发送到供ForEach循环使用的数组中?
谢谢!
答案 0 :(得分:0)
您可以按照here所述将卡阵列用作@EnvironmentObject
。
然后,您可以从两个视图访问该数组,因此只需从NewCardView
附加它即可。
因此,在SceneDelegate中,您需要添加
var MirleftCards: [mirleftCard] = [
mirleftCard(image: Image("beach"), title: "The Beach", description: "The amazing view of the Grande Plage"),
mirleftCard(image: Image("sea"), title: "The Sea", description: "The amazing view of the sea"),
]
进一步,更改
let contentView = ContentView()
到 让contentView = ContentView()。environmentObject(MirleftCards)
从现在开始,您可以从每个视图访问此变量。只需添加
@EnvironmentObject var MirleftCards: [mirleftCard]
在两个视图中到视图结构,然后从工作表中添加新卡。然后应自动更新ContentView。