【问题标题】:Assign Custom TextField data in another View SwiftUI在另一个 View SwiftUI 中分配自定义 TextField 数据
【发布时间】:2021-01-02 05:53:41
【问题描述】:

我正在尝试通过 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 不起作用。如何从文本字段中提取这些文本?

【问题讨论】:

标签: swiftui uitextfield


【解决方案1】:

如果您需要从父级驱动文本,您应该使用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

但是!

您不能在视图生成器中设置creditCard.cardOwnerName = text,就像上面提到的pawello 一样。您应该将此代码移动到它所属的某个位置,例如onChange 或onReceive。 Here is an example of that

所以看看这个:

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 给出了错误。
  • 您应该为每个TextField 定义一个单独的@State var text = ""。如果。你把它们都连接到同一个State,它们总是一样的
  • 嘿@MertKöksal,如果对你有帮助,别忘了点赞。如果这是您问题的答案,请不要忘记将其标记为答案。
猜你喜欢
  • 2023-01-10
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-06
  • 1970-01-01
  • 2019-09-05
相关资源
最近更新 更多