-5

I have this function but the problem is I don't know how to call this function on super.viewDidLoad

  func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        if let text = namaTextField.text {
            if let floatingLabelTextField = textField as? SkyFloatingLabelTextField {
                if(text.characters.count < 3 || !text.contains("@")) {
                    floatingLabelTextField.errorMessage = "Invalid email"
                }
                else {
                    // The error message will only disappear when we reset it to nil or empty string
                    floatingLabelTextField.errorMessage = ""
                }
            }
        }
        return true
    }
Chanchal Chauhan
  • 1,530
  • 13
  • 25
Indra Sen
  • 111
  • 1
  • 9
  • This is a delegate function of UITextField, it is called every time right before there is a change of text of the UITextField for you to determine if the change should happen. There is usually no need to call this explicitly, but if you really do then just pass in the textField, range and replacement string as the method requires. – Ben Ong May 23 '18 at 02:36
  • If you are having problem that is method is not being called when it should just double check if this class of yours is a UITextField delegate and nameTextField.delegate is set to an instance of this class. – Ben Ong May 23 '18 at 02:39
  • 1
    Why do you think you need to call this text field delegate method? You are not supposed to call it yourself. Please explain your goal. – rmaddy May 23 '18 at 02:41
  • You can manually call it (usually, you don't), but you must learn how works the Delegate Pattern first. – Larme May 23 '18 at 07:14

2 Answers2

0

It is textField Delegate method, Every time when you try to change text in TextField this method call before changes so you can choose weather to do change or not.

And as per my experience you can't call it at your own.

singh.jitendra
  • 490
  • 1
  • 9
  • 19
0

That looks like a delegate method from UITextFieldDelegate. Your view controller class should be conforming to UITextFieldDelegate.

Text field delegate methods are not supposed to be called by the VC. They are supposed to be called by the text field.

This particular method is asking you "should I change the this range of text to this replacement string?" and in the method you did some logic and returned true (you answers "yes").

This method will be called whenever the current text of the text field changes to ask you "should this part of the text really change?".

The text field will call this method so don't worry about it. The only thing you should do is to set self as the delegate:

namaTextField.delegate = self
Sweeper
  • 213,210
  • 22
  • 193
  • 313