1

I'm currently formatting my a textfield in xcode, every 5th character I add a hyphen. However I'm having alot of trouble I am currently wanting to check my textfields.text.length then once the length reaches 23 characters the submit button is press-able. So far this works where I have trouble is say if the user enters 23 characters and the button is press-able if the user decided to go back and delete one character there is nothing to update the new text length as I don't know how to catch the delete button of the numberpad... Dose anyone know how to do this?

   - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSString *separator = @"-";
    int seperatorInterval = 5;
    NSString *originalString = [regTextField.text stringByReplacingOccurrencesOfString:separator withString:@""];



    if (![originalString isEqualToString:@""] && ![string isEqualToString:@""]) {

        NSString *lastChar = [regTextField.text substringFromIndex:[regTextField.text length] - 1];
        int modulus = [originalString length] % seperatorInterval;
        [self validateTextFields];

        if (![lastChar isEqualToString:separator] && modulus == 0) {

            regTextField.text = [regTextField.text stringByAppendingString:separator];
        }
    }
    [self validateTextFields];
    return YES;
}

    -(IBAction) validateTextFields {

    if (regTextField.text.length >= 22){
        [submitButton setEnabled:YES]; //enables submitButton
    } 
    else {
        [submitButton setEnabled:NO]; //disables submitButton

    }

}
tinhead
  • 385
  • 2
  • 10
  • 29

1 Answers1

1

Try something like this:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    // Any new character added is passed in as the "text" parameter
    if (!([text isEqualToString:@""] && range.length == 1) && [textView.text length] >=140 ) {
        return NO;
    }
    // For any other character return TRUE so that the text gets added to the view
    return YES;
}

Where the block:

([text isEqualToString:@""] && range.length == 1) 

Is the check for the backspace.

Capturing the backspace on the Number Pad Keyboard

Ahmad Kayyali
  • 8,233
  • 13
  • 49
  • 83