Home > Net >  If textfield is empty set border to red, if we enter text, remove red border
If textfield is empty set border to red, if we enter text, remove red border

Time:11-11

In Swift, I have added border color red to text fields. I want to implement that if we enter any text in it, the textfield border color should be removed, and if again there is no text in it, the border color should again be set to red. Without a click of any button. (programmatically only)

CodePudding user response:

you can do this with following simple code. add this below line in you viewdidload or view configure method

textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged)

change your text field border color or remove the border as you need

@objc func textFieldDidChange(_ textField: UITextField) {
        if (textField.text!.isEmpty)
        {
            // change your textfield border color
        }
        else
        {
            // remove text field border or change color
        }
    }

CodePudding user response:

This should help:

if self.yourTextField.text.isEmpty
{
   self.yourTextField.layer.borderColor = UIColor.red.cgColor
   self.yourTextField.layer.borderWidth = 1
}
else
{
   self.yourTextField.layer.borderWidth = 0
}
  • Related