UITextField strange behavior when delete symbol in

2019-08-17 04:39发布

问题:

When I push my ViewController one of the textfield must be have text, I make it and it is all good

 cell.textFieldMain.text = [NSString stringWithFormat:@"+7 (%@) %@-%@",[num substringToIndex:3], [num substringWithRange:NSMakeRange(3, 3)], [num substringFromIndex:6]];

I have method that put cursor in the needed place, because I make template for textfield

My method:

- (void)setCurcorForTextField:(UITextField *)textField position:(NSInteger)position
{
UITextPosition *newPosition = [textField positionFromPosition:textField.beginningOfDocument offset:position];
UITextRange *newRange = [textField textRangeFromPosition:newPosition toPosition:newPosition];
[textField setSelectedTextRange:newRange];
}

In my method for changing I have

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
 //other conditions
 else {
        textField.text = [NSString stringWithFormat:@"+7 (%@) %@-%@",[num substringToIndex:3], [num substringWithRange:NSMakeRange(3, 3)], [num substringFromIndex:6]];
        if (length == 7)
            [self setCurcorForTextField:textField position:14];
        else if (length == 8)
            [self setCurcorForTextField:textField position:15];
        else if (length == 9)
            [self setCurcorForTextField:textField position:16];
        else if (range.length)
            [self setCurcorForTextField:textField position:17];
    }
}
return YES;

So when I first try to delete last character I take empty field, but I must have something like +7 (123) 456-789 (phone number with 10 numbers without last deleted. In other cases it is work fine. And even when I push this ViewController in next time, and tableview with this textfield created again I have no trouble and all work fine.

When I push mu ViewController I see

I try to delete last character and empty field appear

But in other cases when I even push this ViewController again all work fine and I can delete last character

When I delete all characters and type new number and then and editing, after beginning editing this field and try to delete - all work fine. Always work fine^ but only first time work bad