2011-02-24 132 views

回答

1

您可以創建兩個按鈕就OK和Cancel.Then通過檢查文本框的文本(文本長度)添加這兩個作爲UIAlertView.Now子視圖,您可以執行啓用和禁用操作。

0

不知道您的應用程序的上下文,以下可能不適用 - 但你有沒有讀iOS Human Interface Guidelines?這聽起來好像你可能會更好地找到替代UIAlertView,如果這是經常會顯示給用戶的東西。

0

與您的問題並不真正相關,但如果您不希望應用程序被拒絕,請不要修改默認的UIAlertView。如果我沒有錯,就是在alertview中添加文本框,不是嗎?像登錄視圖一樣。你應該創建你自己的觀點。

因此,關於你的問題,創建你的視圖,設置按鈕已禁用,並委託UITextFields。當

- (void)textFieldDidBeginEditing:(UITextField *)textField; 

被調用,啓用這些按鈕。

37

只有張貼這更新,因爲iOS 5的響應:

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView 
{ 
    UITextField *textField = [alertView textFieldAtIndex:0]; 
    if ([textField.text length] == 0) 
    { 
    return NO; 
    } 
    return YES; 
} 

UPDATE:iOS的8自從蘋果都贊成UIAlertController的過時的UIAlertView中。不再有一個委託調用alertViewShouldEnableFirstOtherButton:

因此,你會通過UITextFieldTextDidChangeNotification 設置按鈕enabled屬性一個TextView添加到提醒與

  • (無效)addTextFieldWithConfigurationHandler:(無效(^ )(*的UITextField文本字段))configurationHandler
[<#your alert#> addTextFieldWithConfigurationHandler:^(UITextField *textField) { 
textField.delegate = self; 
textField.tag = 0; //set a tag to 0 though better to use a #define 
}]; 

然後實現委託方法

  • (無效)textFieldDidBeginEditing:(的UITextField *)文本框
- (void)textFieldDidBeginEditing:(UITextField *)textField{ 
//in here we want to listen for the "UITextFieldTextDidChangeNotification" 

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

} 

當文本框的文字變化,它會調用調用「textFieldHasText: 「並傳遞NSNotification *

-(void)textFieldHasText:(NSNotification*)notification{ 
//inside the notification is the object property which is the textField 
//we cast the object to a UITextField* 
if([[(UITextField*)notification.object text] length] == 0){ 
//The UIAlertController has actions which are its buttons. 
//You can get all the actions "buttons" from the `actions` array 
//we have just one so its at index 0 

[<#your alert#>.actions[0] setEnabled:NO]; 
} 
else{ 

[<#your alert#>.actions[0] setEnabled:YES]; 
} 
} 

不要忘記在完成後刪除觀察者

+2

我希望我能投了不止一次。非常感謝。 – 2013-02-22 04:20:03

4

我想通過添加這個來擴展Ryan Forsyth的答案。如果添加一個默認樣式的UIAlertView,如果您嘗試訪問一個沒有文本字段的文本字段,則可能會遇到超出範圍的異常,因此請首先檢查您的視圖樣式。

-(BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView*)alertView 
{ 
    if(alertView.alertViewStyle == UIAlertViewStyleLoginAndPasswordInput || 
     alertView.alertViewStyle == UIAlertViewStylePlainTextInput || 
     alertView.alertViewStyle == UIAlertViewStyleSecureTextInput) 
    { 
     NSString* text = [[alertView textFieldAtIndex:0] text]; 
     return ([text length] > 0); 
    } 
    else if (alertView.alertViewStyle == UIAlertViewStyleDefault) 
     return true; 
    else 
     return false; 
}