UITextField - adding a character after entering the 1st character when typing

I have a UITextField that will contain the height value. I want to format the value of a field when a user enters text in a UITextField. for example, if I want to enter the value "5 feet 10", the stream will be:

1. Enter 5 2. " ft " is appended immediately after I type 5 with leading & trailing space. 

My code is as follows:

 -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if ( [string isEqualToString:@""] ) return YES; // currHeight Formatting if ( textField == currHeight ) { if (currHeight.text.length == 1) { currHeight.text = [NSString stringWithFormat:@"%@ ft ", currHeight.text]; } } return YES; } 

I am stuck at the point where I enter 5, nothing happens. I have to press any button to add "ft".

Can I do this without clicking anything?

+6
source share
2 answers

-shouldChangeCharactersInRange is called before the change to the text field occurs, so the length is still 0 (see Using `textField: shouldChangeCharactersInRange:`, how do I get text, including the current typed character? ). Try instead:

 - (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString: (NSString*) string { if (textField == currHeight) { NSString *text = [textField.text stringByReplacingCharactersInRange:range withString: string]; if (text.length == 1) { //or probably better, check if int textField.text = [NSString stringWithFormat: @"%@ ft ", text]; return NO; } } return YES; } 
+6
source

When this function is called, currHeight.text still has a length of 0. Text returns only 5 after returning YES.

The way to do what you want to do is to check if currHeight.text.length is 0, string.length is 1, and the first character of the string is numeric.

+1
source

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


All Articles