0

I am trying to assign credit card information(text: $data) through customTextField to another View.

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

To this View called 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

But CustomTextField.text won't work. How can I pull those texts from textfield?enter image description here

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
Mert Köksal
  • 817
  • 1
  • 7
  • 26
  • This might help you as well: [How to detect live changes on TextField in SwiftUI?](https://stackoverflow.com/questions/57875550/how-to-detect-live-changes-on-textfield-in-swiftui) – pawello2222 Sep 15 '20 at 13:23
  • This is another issue, please do not change the question when you apply some new code and new errors happen ;) Comment or Ask a new question instead – Mojtaba Hosseini Sep 15 '20 at 14:25

1 Answers1

0

If you need to drive the text from the parent, you should use a Binding instead of State:

struct CustomTextField: View {
    @Binding var data: String
    ,,,
}

then you can access it from the parent as you wish like:

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

Also, remember that you should not change any State from outside of the body block. (So you can make it private(set))

And you can access it directly from the text:

creditCard.cardOwnerName = text

BUT!

You can not set creditCard.cardOwnerName = text in the view builder as pawello mentioned. You should move this code somewhere it belongs to like onChange or onReceive. Here is an example of that

So take a look at this:

CustomTextField(data: $text, tFtext: "Kartin Uzerindeki Isim", tFImage: "user")
    .onReceive(text.publisher, perform: { _ in
        print(text) // could be creditCard.cardOwnerName = text
    })
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278