Ahmed
Ahmed

Reputation: 1359

How to determine which Textfield is being changed in SwiftUI

I have the following 2 textfield as shown in my code my question how can I differentiate which text field is being changed

TextField("", text: $phoneAuthViewModel.firstCodeField)
    .frame(width:40, height: 48, alignment: .center)
     .background(Color(red: 1, green: 1, blue: 1, opacity: 0.3))
     .foregroundColor(.black)
     .cornerRadius(5)
     .keyboardType(.phonePad)
     .accentColor(.white)
     .multilineTextAlignment(.center)
     .onChange(of: phoneAuthViewModel.firstCodeField, perform: editingChanged(_:))


TextField("", text: $phoneAuthViewModel.country)
    .frame(width:40, height: 48, alignment: .center)
     .background(Color(red: 1, green: 1, blue: 1, opacity: 0.3))
     .foregroundColor(.black)
     .cornerRadius(5)
     .keyboardType(.phonePad)
     .accentColor(.white)
     .multilineTextAlignment(.center)
     .onChange(of: phoneAuthViewModel.country, perform: editingChanged(_:))

func editingChanged(_ value: String) {
   
    
}

Now How can i determine which textfield is being edited. Is it possible to pass an agrument with editingChanged Function

Upvotes: 1

Views: 93

Answers (1)

Asperi
Asperi

Reputation: 258443

Just use different functions as callbacks, like

TextField("", text: $phoneAuthViewModel.firstCodeField)
     .onChange(of: phoneAuthViewModel.firstCodeField, perform: codeChanged(_:))


TextField("", text: $phoneAuthViewModel.country)
     .onChange(of: phoneAuthViewModel.country, perform: countryChanged(_:))

func codeChanged(_ value: String) {
  // handle code changed here
}

func countryChanged(_ value: String) {
  // handle country changed here
}

Upvotes: 1

Related Questions