UIAlertView textfield capture onchange

荒凉一梦 提交于 2019-12-25 00:21:10

问题


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];


来源:https://stackoverflow.com/questions/13268358/uialertview-textfield-capture-onchange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!