0

let me explain my question with an example

I have a UITextField and want to limit its text and also have a UILabel that tells how many more characters can the user type. Thus when I start typing, everything is running great, I am using this delegate function:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {}

But when i assign text like this : textField.text = "Hello", the above mention method is not called and thus the counter label value is not changed,

I have also tried: textField?.addTarget(self, action: #selector(txtFieldChanged), for: .allEditingEvents)

but no luck

user832
  • 638
  • 4
  • 15
  • Why you are assigning a value, because you need to take the input from the textfield ,, so what is the use of assigning a value statically to textfield.. – Vignesh Davins Jun 29 '17 at 05:17
  • 1
    When assigning text programatically by textField.text = "Hello", delegate methods will not be called – Aakash Jun 29 '17 at 05:21
  • https://stackoverflow.com/questions/7010547/uitextfield-text-change-event maybe this could help – Akash Singh Sisodia Jun 29 '17 at 05:23
  • You need to call them manually after setting the text if you still want those methods to fire – Aakash Jun 29 '17 at 05:27
  • @VigneshDavins think of it as a WhatsApp status, when i click on Available or Busy, the text in textfield changes – user832 Jun 29 '17 at 05:28

1 Answers1

1

According to you question when you are assigning text to your textfield like "hello" then you have to calculate the textfield length in your view did load method and set the counter there. And when you will start typing in you text field your delegate will be called.

double left = 500 - textView.text.length ;

lblcounter.text = [NSString stringWithFormat:@"%.0f character left",left];
Raman Srivastava
  • 398
  • 1
  • 13