Search code examples
iosobjective-cuitextfielduialertcontroller

shouldChangeCharactersInRange is not getting called


I have a textfield in the alertview called phoeNumberTF.

phoneNumberTF.delegate = self;

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter your phone number" message:nil preferredStyle:UIAlertControllerStyleAlert];

[alert addAction:[UIAlertAction
                  actionWithTitle:@"Send"
                  style:UIAlertActionStyleDefault
                  handler:^(UIAlertAction * action)
                  {
                      NSArray * textfields = alert.textFields;
                      phoneNumberTF = textfields[0];
                      [self sendPhoneNumber:phoneNumberTF.text];
                  }]];

shouldChangeCharactersInRange delegate method is not getting called

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

}

Solution

  • phoneNumberTF is not a part of UIAlertController so no need of delegate for this phoneNumberTF.delegate = self;

    add the configuration delegate to your UIAlertController

     UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter your phone number" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) 
    {
    
    textField.delegate = self;
    }]; 
    

    for more info you get the sample here