'How to identify which UITextView is selected

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


Solution 1:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 matt