2011-12-02 83 views

回答

5

答案由@beryllium只告訴故事的一部分。

事實上,正確的驗證輸入文本字段在可可,你應該使用連接到您的文本字段細胞的NSFormatter,然後在你的NSTextFieldDelegate應實現方法:control:didFailToFormatString:errorDescription:。在這個委託方法中,您可以提示用戶更正他們的輸入。

所有你需要在你的NSFormatter子做的是這樣的:

@implementation RKTextFormatter 

- (NSString*)stringForObjectValue:(id)object 
{ 
    return (NSString*)object; 
} 

- (BOOL)getObjectValue:(id*)object forString:(NSString*)string errorDescription:(NSString**)error { 

    BOOL stringPassesTest = NO; 

    //put your test here 

    if(!stringPassesTest) 
    { 
     //set the error and return NO 
     if(error) 
      *error = [NSError errorWithDomain:@"YourErrorDomain" code:1 userInfo:[NSDictionary dictionaryWithObject:@"It's a bingo" forKey:NSLocalizedDescriptionKey]]; 
     return NO; 
    } 

    //otherwise, just assign the string 
    *object = string; 
    return YES; 
} 
@end 

你會格式化分配給您的文本字段,如下所示:

RKTextFormatter* formatter = [[RKTextFormatter alloc] init]; 
[[textField cell] setFormatter:formatter]; 

,然後在NSTextFieldDelegate你處理任何無效輸入:

- (BOOL)control:(NSControl *)control didFailToFormatString:(NSString *)string errorDescription:(NSString *)error 
{ 
//display an alert, obviously it would be more useful than this 
NSAlert* alert = [NSAlert alertWithMessageText:@"You have failed me for the last time" defaultButton:@"Revise Input" alternateButton:nil otherButton:nil informativeTextWithFormat:@"%@",error]; 

[alert beginSheetModalForWindow:control.window modalDelegate:nil didEndSelector:NULL contextInfo:NULL]; 

//if you return NO here, the user's input will not be accepted 
//and the field will remain in focus 
return NO; 
} 
+1

謝謝,幾天後我回到您的解決方案。我還有一個問題,除了我的自定義提醒之外,還會顯示另一個彈出窗口。我怎樣才能壓制它? (我嘗試刪除NSError行,但它仍然存在。 – aneuryzm

1

嘗試使用此代碼:

- (IBAction)pushBtn:(id)sender { 

    if(self.textfield.stringValue.length == 0){ 
     NSAlert * alert = [NSAlert alertWithMessageText:@"Error" 
              defaultButton:@"OK" 
             alternateButton:nil 
              otherButton:nil 
           informativeTextWithFormat:@"Enter a text into text field"]; 

     [alert beginSheetModalForWindow:self.window 
          modalDelegate:self 
         didEndSelector:@selector(alertDidHidden:) 
          contextInfo:nil]; 
     //[alert runModal]; - more simple way 
    } 
} 

-(void)alertDidHidden:(NSAlert *)alert{ 

} 
4

如果用戶點擊應用且NSTextField爲空,則彈出框應顯示 表示該字段不能爲空。

請不要這樣做。你可以比這更聰明。

不用花時間編寫警報對話框來處理「意外」情況,而是將其投入創建一種方法,以防止問題首先發生:保持禁用Apply按鈕,直到具有適當的值已輸入文本字段

另外,如@Rob Keniger提到的,您應該考慮使用NSFormatter來驗證輸入以確保它是合適的類型。

+1

如果您的表單需要超過「已設置」,該怎麼辦?這不能解決這個問題。 –

+0

請解釋您的意思是「表單需要多於「已設置」「。 – NSGod