在另一个视图 SwiftUI 中分配自定义 TextField 数据

Assign Custom TextField data in another View SwiftUI

我正在尝试通过 customTextField 将信用卡信息(文本:$data)分配给另一个视图。

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 将不起作用。我如何从文本字段中提取这些文本?

如果你需要从父级驱动文本,你应该使用 Binding 而不是 State:

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)
        }
    }
}

此外,请记住您不应更改 body 块之外的任何 State。 (所以你可以做到private(set)

并且您可以直接从文本中访问它:

creditCard.cardOwnerName = text

但是!

您不能像 pawello 提到的那样在视图生成器中设置 creditCard.cardOwnerName = text。您应该将此代码移动到它所属的某个位置,例如 onChangeonReceive

所以看看这个:

CustomTextField(data: $text, tFtext: "Kartin Uzerindeki Isim", tFImage: "user")
    .onReceive(text.publisher, perform: { _ in
        print(text) // could be creditCard.cardOwnerName = text
    })