UIAlertView textfield capture onchange

2019-08-17 00:13发布

问题:

I'm trying to implement custom AlertView.

The idea is to have alertview with textfield and cancel button.

What i can't do is to check textfield live for entered characters. I know i can do it using – alertViewShouldEnableFirstOtherButton: but i don't want another button. I wish to do the same just without button.

In android you can add listeners to textfields onchange.

Tried to do it using this uitextfield function, but it doesn't get called live or maybe i'm using it in a wrong way.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    textField = [alert textFieldAtIndex:0];
    if ([textField.text length] == 0)
    {
        NSLog(@"Hello");
        return NO;
    }
    return NO;
}

So how to do this properly?

回答1:

try this

    UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"New List Item", @"new_list_dialog")
                                                          message:@"this gets covered" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
   UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
    myTextField.delegate = self;
    [myTextField setBackgroundColor:[UIColor whiteColor]];
    [myAlertView addSubview:myTextField];
    [myAlertView show];
    [myAlertView release];

and textfield method

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSLog(@" %@", [textField.text stringByReplacingCharactersInRange:range withString:string]);
    return YES;
}


回答2:

You can add observer for the UITextFieldTextDidChangeNotification which will be posted whenever the text changes in textfield.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(controlTextDidChange:)
   name:UITextFieldTextDidChangeNotification object:[alert textField]];

selector is below:

- (void)controlTextDidChange:(NSNotification *)notification {
{
    if ([notification object] == [alert textField]) 
    {
      // [alert textField] has changed
    }
}

EDIT : remove Observer when finish doing

[[NSNotificationCenter defaultCenter] removeObserver:UITextFieldTextDidChangeNotification];