簡體   English   中英

UIAlertView文本字段捕獲onchange

[英]UIAlertView textfield capture onchange

我正在嘗試實現自定義AlertView。

想法是使Alertview具有文本字段和“取消”按鈕。

我不能做的是實時檢查輸入的字符的文本字段。 我知道我可以使用– alertViewShouldEnableFirstOtherButton:來做到這– alertViewShouldEnableFirstOtherButton:但是我不想要另一個按鈕。 我希望沒有按鈕也能這樣做。

在android中,您可以將偵聽器添加到文本字段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;
}

那么如何正確地做到這一點呢?

嘗試這個

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

和文本字段方法

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

您可以為UITextFieldTextDidChangeNotification添加觀察者,每當texttextfield changes時,該觀察者都會發布。

[[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
    }
}

編輯finish remove Observer

[[NSNotificationCenter defaultCenter] removeObserver:UITextFieldTextDidChangeNotification];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM