Limit the number of characters in a UITextField where input is from the user interface

I have a UITextField for which I get input from some buttons that are part of the user interface (so the input does not come from the virtual keyboard of the phone). I want to limit this number of characters. I tried to use shouldChangeCharactersInRange , but it only works if the input comes from the virtual keyboard, and it doesn't work if the input comes from buttons in the user interface. Is there anyway I can solve this problem without programmatically counting the characters in the text box every time I want to update it?

Thank you, Mihai Fonoaj

+4
source share
4 answers

Since you programmatically make changes to the UITextField, as soon as the user clicks the appropriate buttons in the user interface, you must keep track of the number of characters entered using the counter. Increase the counter every time the corresponding user interface button is touched. Update the text box only if the counter value is <= the maximum allowed value. characters.

+2
source

Implement the delegate method UITextField shouldChangeCharactersInRange:

set the method to return YES when the string length is less than your maximum value.

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField.text.length<3) { return YES; } return NO; } 
+3
source

Check the length of the string property on the text box before making changes.

0
source

There is a textRectForBounds Property

0
source

Source: https://habr.com/ru/post/1299449/


All Articles