在另一个视图SwiftUI中分配自定义文本字段数据
我正试图通过customTextField将信用卡信息(文本:$data)分配给另一个视图在另一个视图SwiftUI中分配自定义文本字段数据,swiftui,uitextfield,Swiftui,Uitextfield,我正试图通过customTextField将信用卡信息(文本:$data)分配给另一个视图 struct CustomTextField: View { @State var data : String = "" var tFtext: String = "" var tFImage: String = "" var body: some View { HStack {
struct CustomTextField: View {
@State var data : String = ""
var tFtext: String = ""
var tFImage: String = ""
var body: some View {
HStack {
Image(tFImage)
.resizable()
.frame(width: 20, height: 20)
.padding()
TextField(tFtext, text: $data)
.padding()
.font(Font.custom("SFCompactDisplay", size: 16))
.foregroundColor(.black)
}
.background(RoundedRectangle(cornerRadius: 10))
.foregroundColor(Color(#colorLiteral(red: 0.9647058824, green: 0.9725490196, blue: 0.9882352941, alpha: 1)))
}
}
这个视图称为CardInfo
struct CardInfo : View {
var creditCard: CreditCard
@State var isSaved: Bool = false
var body: some View {
VStack {
CustomTextField(tFtext: "Kartin Uzerindeki Isim", tFImage: "user")
.textContentType(.givenName)
creditCard.cardOwnerName = CustomTextField.text
但是CustomTextField.text不起作用。如何从textfield中提取这些文本?如果需要从父级驱动文本,应使用
绑定而不是状态
:
struct CustomTextField: View {
@Binding var data: String
,,,
}
然后,您可以根据需要从父级访问它:
struct CardInfo : View {
@State var isSaved: Bool = false
@State private(set) var text = ""
var body: some View {
VStack {
CustomTextField(data: $text, tFtext: "Kartin Uzerindeki Isim", tFImage: "user")
.textContentType(.givenName)
}
}
}
另外,请记住,您不应该从正文
块外部更改任何状态
。(因此您可以将其设置为私有(set)
)
您可以直接从文本中访问它:
creditCard.cardOwnerName = text
但是
您不能像pawello提到的那样在视图生成器中设置creditCard.cardOwnerName=text
。您应该将此代码移动到它所属的某个位置,如onChange
或onReceive
看看这个:
CustomTextField(data: $text, tFtext: "Kartin Uzerindeki Isim", tFImage: "user")
.onReceive(text.publisher, perform: { _ in
print(text) // could be creditCard.cardOwnerName = text
})
您可能还需要解释在何处设置
creditCard.cardOwnerName=text
。在问题中,OP尝试在VStack
中使用creditCard.cardOwnerName=CustomTextField.text
…我已更改了答案,使其更像原始问题。感谢您提到pawello:)不幸的是,creditCard.cardOwnerName=text出现错误。您应该为每个文本字段
定义一个单独的@State var text=”“
。如果。如果你将所有人都连接到同一个州
,他们将永远是同一个@MertKöksal,如果这对你有帮助,别忘了向上投票。如果这是您问题的答案,请不要忘记将其标记为“答案”。这可能也会对您有所帮助:这是另一个问题,当您应用一些新代码时,请不要更改该问题,否则会发生新错误;)改为评论或提出新问题