-1

I have several UITextFields (with outlets) in a viewController and want to use shouldChangeTextIn to validate user input (similar to Allow only Numbers for UITextField input).

How can I identify which textField was selected? (If possible, I would prefer to identify it by the outlet name I gave it and not have to resort to using tags.)

@IBOutlet weak var fld1: UITextView!
// more outlets ...
@IBOutlet weak var fld20: UITextView!

textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) { 
    print("textField \(outletName) was modified")
}
Greg
  • 667
  • 8
  • 19
  • Using `debugPrint("textView: \(textView)")`, I see that each textField has its own unique identifier - alternatively, is there a way to get the outlet's name from that id? `textView: ; layer = ; contentOffset: {0, 0}; contentSize: {240, 83}; adjustedContentInset: {0, 0, 0, 0}>"` – Greg Mar 29 '22 at 21:34
  • 1
    Use the === operator to compare fld1 or fld20 to textView – Rob C Mar 29 '22 at 22:46
  • "If possible, I would prefer to identify it by the outlet name I gave it and not have to resort to using tags" Absolutely correct instincts! – matt Mar 30 '22 at 01:32
  • Did you try _anything?_ I would have expected simple `==` test to work (because by default it falls back on `===`). Indeed, even a simple `switch` works (and I've given that as an answer). – matt Mar 30 '22 at 01:33

1 Answers1

1

You cannot magically generate the variable name from the textView reference; most computer languages don't work that. But what's wrong with:

switch textView {
case fld1: // do something
case fld20: // do something else
default: break
}

However, your use of outlet names each of which ends in a number is a horrible code smell. Think again about how to do this. If you have 20 text views, for instance, why didn't you make a single outlet — an outlet collection? That way, you have just one array of text views, and now if you really need to, you can look to see what index this text view is at, within that array.

That's a very good trick for pairing each text view with some other interface object, for example. If you have two arrays, of the same length, you can use the index of the text view as the index into the second array.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • I didn't know to compare it to `textView`. Those outlet names were only to use for the example for this question. I learned to use useful variable names a long time ago! I did not know I could use a collection in this case. Always good to learn new things! – Greg Mar 30 '22 at 14:16