微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在另一个View SwiftUI中分配自定义TextField数据

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

enter image description here

解决方法

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

此外,请记住,您不应在State块之外更改任何body。 (因此您可以将其设为private(set)

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

creditCard.cardOwnerName = text

但是!

您不能如pawello所述在视图构建器中设置creditCard.cardOwnerName = text。您应该将此代码移到它所属的某个地方,例如onChangeonReceiveHere is an example of that

所以看看这个:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。