2012-02-08 104 views
2

我有一個帶有textField的UIAlertView和兩個按鈕:保存&取消。點擊保存按鈕時,我正在檢查文本字段是否爲空,如果是,我只想將textFields佔位符更改爲:@「請輸入名稱」並將警報視圖保留在屏幕上。但它會被自動解僱。保持UIAlertView顯示

我該如何重寫?

+1

檢查這個答案在這裏一個更好的方式來處理您的情況:http://stackoverflow.com/questions/1947783/prevent-uialertview-from-dismissing – jonkroll 2012-02-08 20:23:16

+0

看來你已經子類覆蓋默認解僱行爲,請參閱:[http://stackoverflow.com/questions/2051402/is-it-possible-to-not-dismiss-a-uialertview](http://stackoverflow.com/questions/2051402/is-it -possible-to-not-dismiss-a-uialertview) – GregularExpressions 2012-02-08 21:41:36

+0

謝謝你們,但正如我在下面向Brendan寫的那樣,我決定做出自己的警報視圖。感謝您抽出時間和評論:) – 2012-02-09 20:33:17

回答

6

將目標添加到子類警報視圖中的文本字段。你也可以繼承的alertView並不能排除as described in this post

[[alertView textFieldAtIndex:0] addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged]; 

然後編寫一個名爲textFieldDidChange函數,用來檢查你的alertView當前文本框,並設置一個布爾值,所以你知道是否要解除警報。

- (void) textFieldDidChange 
{ 
    NSString *alertViewText = [[alertView textFieldAtIndex:0] text]; 

    if ([alertViewText isEqualToString:@""]) { 
    [alertView setMessage:@"Enter a name please."]; 
    } else { 
    [alertView setMessage:@"Default Message"]; 
    } 
} 

*另外,我建議禁用「保存」時,它是空的,而不必子類。 *

- (void) textFieldDidChange 
{ 
    NSString *alertViewText = [[alertView textFieldAtIndex:0] text]; 

    if ([alertViewText isEqualToString:@""]) { 
    [alertView setMessage:@"Enter a name please."]; 
    for (UIViewController *view in alertView.subview) { 
     if ([view isKindOfClass:[UIButton class]]) { 
      UIButton *button = (UIButton *)view; 
      if ([[[button titleLabel] text] isEqualToString:@"Save"]) 
      [button setEnabled:NO]; 
     }  
    } 
    } else { 
    [alertView setMessage:@"Default Message"]; 
    for (UIViewController *view in alertView.subview) { 
     if ([view isKindOfClass:[UIButton class]]) { 
      UIButton *button = (UIButton *)view; 
      if ([[[button titleLabel] text] isEqualToString:@"Save"]) 
      [button setEnabled:YES]; 
     }  
    } 
    } 
} 
+0

哇,感謝您的回覆布倫丹。我認爲這會容易得多。所以,我決定從頭開始製作自己的AlertView。再次感謝! :) – 2012-02-09 20:31:59

+0

我目前在應用程序中實現的替代方法並不困難,並給你很大的權力。例如,您可以在用戶輸入任何不允許的名稱時禁用「保存」按鈕。這可能包括一個空字符串,一個已經在使用的名稱或一個禁用的名字(例如粗俗的詞或關鍵字)。它還使得alertView:willDismissWithButtonIndex不必進行任何錯誤檢查,因爲用戶只能針對無效名稱點擊「取消」。 – brendan 2012-02-09 21:00:56

+0

是的,我明白了,這只是我已經開始在我的應用中實現自定義通知,並且我已經決定我還需要重新設計AlerView。這對我來說會更多工作和更復雜,然後修改本機警報 – 2012-02-09 21:03:25