gpt4 book ai didi

SwiftUI 将保存的值传递给父 View

转载 作者:行者123 更新时间:2023-12-04 09:30:57 28 4
gpt4 key购买 nike

我对 SwiftUI 相当陌生,我正在尝试找出将数据从 subview 传递给父 View 的最佳方法?
感谢我来自 Javascript (React) 背景的帮助,所以这对我来说有点不同
我的 subview 的工作方式是用户单击图像以选择该图像。
我有 @State 绑定(bind),它保存了 imgUrl,它是一个引用 Assets 中名称的字符串。
我只是不确定将该值传递给父组件的最佳方式。
这是 subview (imageSelector)

struct ImageSelector: View {
@State private var windowImgs = ["1", "2", "3","4","5","6","7","8","9","10","11","12","13", "14","15","16","17","18"]

@State private var imgPicked = ""


var body: some View{
ScrollView(Axis.Set.horizontal, showsIndicators: true){
HStack{
ForEach(0..<18){num in
Button(action:{
self.imgPicked = self.windowImgs[num]
print(self.imgPicked)
}){
Image("\(self.windowImgs[num])")
.renderingMode(.original)
.resizable()
.cornerRadius(4)
.frame(width: 100, height: 100)
}
}
}
}
}
}
这是父 View (AddCounterForm)
struct AddCounterForm: View {
@Environment(\.presentationMode) var presentationMode
@State private var pickedImg: String = "defaultImg"
@State private var price: String = "0.0"
@State private var qty: String = "0"
var body: some View {
VStack (spacing: 40){
HStack {
Button("Cancel"){
self.presentationMode.wrappedValue.dismiss()
}
.foregroundColor(.red)
Spacer()
Button("Save"){

}
}
HStack {
VStack (spacing: 20){
TextField("Window type", text: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Value@*/.constant("")/*@END_MENU_TOKEN@*/)
TextField("Window location", text: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Value@*/.constant("")/*@END_MENU_TOKEN@*/)
}
.textFieldStyle(RoundedBorderTextFieldStyle())
Image(pickedImg)
.resizable()
.cornerRadius(4)
.frame(width: 90, height: 90)
.padding(.leading)
}

HStack {
Text("Price")
TextField("", text:$price)
.frame(width: 70)
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.numberPad)
Spacer()
Text("Qty")
TextField("", text:$qty)
.frame(width: 70)
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.numberPad)
}
VStack {
Text("Select an image")
.foregroundColor(.blue)
ImageSelector()
.padding(.bottom)

Button("Use your own image"){
//method
}
.frame(width: 180, height: 40)
.background(Color.blue)
.clipShape(Capsule())
.foregroundColor(.white)
.padding(.top)
}

}
.padding()
}
}
感谢@Asperi 和@neverwinterMoon 提供的预览解决方案
struct ImageSelector_Previews: PreviewProvider {
static var previews: some View {
PreviewWrapper()
}
}
结构 PreviewWrapper:查看 {
@State(initialValue: "") var imgPicked: String
var body: some View {
ImageSelector(imgPicked: $imgPicked)
}
}

最佳答案

在这种情况下,Binding 是最合适的

struct ImageSelector: View {
@Binding var imgPicked: String
并使用
ImageSelector(imgPicked: $pickedImg)
.padding(.bottom)

关于SwiftUI 将保存的值传递给父 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62845833/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com