-1

I have a form with a UIView wrapping around a UILabel and UITextField. When a user enters the field I would like to change the colour of the label and the border colour of the view container.

If I call a function on the firstResponder I will need to find the text field's corresponding label and view copntainer.

I thought to have a firstResonder function for each field and in each function send the corresponding outlets (textfield, label, view) to a function which handles the colour changes for the label and view border.

This is not terrible but I and sure this can be accomplished more efficiently.

Any pointers please.

edit:

I changed my requirement slightly to place the label inside the textfield and highlight the textfield border instead of the encapsulating view.

This is what I ended up with:

override func viewDidLoad() {
    super.viewDidLoad()
    firstNameLabel.connect(with: firstName)
}

extension UILabel {
@objc
func editingChanged(textField: UITextField) {
}

@objc
func editingDidBegin(textField: UITextField) {
    self.textColor = UIColor.blue
    textField.layer.borderColor = UIColor.blue.cgColor
}

@objc
func editingDidEnd(textField: UITextField) {
    self.textColor = UIColor.green
    textField.layer.borderColor = UIColor.green.cgColor
}

func connect(with textField:UITextField){
    //textField.addTarget(self, action: #selector(UILabel.editingChanged(textField:)), for: .editingChanged)
    textField.addTarget(self, action: #selector(UILabel.editingDidBegin(textField:)), for: .editingDidBegin)
    textField.addTarget(self, action: #selector(UILabel.editingDidEnd(textField:)), for: .editingDidEnd)
    
    
    textField.layer.borderColor = UIColor.gray.cgColor
    textField.layer.borderWidth = 1;
    textField.layer.cornerRadius=10
}
}
Bobby
  • 17
  • 3

1 Answers1

0

The usual thing is to give each member of each group a corresponding tag. Since viewWithTag drills down to find any view with the given tag, the problem is solved if you know how to convert the tag value of the view you have to the tag value of the view you want.

For example, text field 10, view 110, label 210; text field 11, view 111, label 211; and so on. Or whatever system suits your fancy.

Alternatively just walk the view hierarchy. The view is the text field's superview, and the label is the first subview of the view that is a label.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • It will be useful to have on hand the utility that I show at the start of https://stackoverflow.com/a/66827533/341994. – matt Jul 23 '22 at 02:25