UIAlertView文本字段捕获onchange

时间:2012-11-07 11:01:29

标签: objective-c ios uitextfield uialertview

我正在尝试实现自定义AlertView。

我们的想法是使用文本字段和取消按钮提供alertview。

我不能做的是检查输入字符的文本字段。我知道我可以使用– alertViewShouldEnableFirstOtherButton:来做,但我不想要另一个按钮。我希望在没有按钮的情况下做同样的事情。

在android中,您可以将监听器添加到text上的onchange。

尝试使用这个uitextfield函数来完成它,但它不会被实时调用,或者我可能以错误的方式使用它。

- (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;
}

那么如何正确地做到这一点?

2 个答案:

答案 0 :(得分:2)

试试这个

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

和textfield方法

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

答案 1 :(得分:1)

您可以为UITextFieldTextDidChangeNotification添加观察者,只有在textchanges textfield时才会发布观察者。

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

选择器如下:

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

时,

编辑Observer finish

[[NSNotificationCenter defaultCenter] removeObserver:UITextFieldTextDidChangeNotification];
相关问题