2010-10-10 44 views
1

我想獲得如果uitextfield是空的,並且它是否在ibaction中運行以下代碼。如何檢測uitextfield長度

float uu = ([u.text floatValue]); 
float ss = ([s.text floatValue ]); 
float aa = ([a.text floatValue ]); 


float x1float = sqrt((uu * uu) +(2*aa*ss)); 


v.text = [[NSString alloc]initWithFormat:@"%f", x1float]; 

其中v.text是的UITextField

回答

5

我假設你在這裏的主要挑戰不是簡單地檢查UITextFieldtext屬性是否爲空,裏面的文字,但得到它來執行檢查用戶類型。爲了簡單地檢查文本字段是否爲空,你只是做:

if (aTextField.text == nil || [aTextField.text length] == 0) 

但是,如果你想獲得文本字段設置爲「自動」進行計算時,它變空,請執行下列操作:設置UITextField的代表。在文本字段中更改任何字符之前調用代理的textField:shouldChangeCharactersInRange:replacementString:方法。在該方法中,這樣做:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
    [self performSelector:@selector(updateEmptyTextField:) withObject:textField afterDelay:0]; 
    return YES; 
} 

您的延遲之後執行updateEmptyTextField因爲UITextField尚未應用於其代表剛剛批准的變化。然後,在updateEmptyTextField:做這樣的事情:

- (void)updateEmptyTextField:(UITextField *)aTextField { 
    if (aTextField.text == nil || [aTextField.text length] == 0) { 
     // Replace empty text in aTextField 
    } 
} 

注:直到用戶開始在文本字段中鍵入您可能需要手動運行一次檢查時,首先顯示您的看法,因爲textField:shouldChangeCharactersInRange:replacementString:將不會被調用。

+0

偉大的職位非常感謝 – 2010-10-10 19:30:01

+0

不能使用[self updateEmptyTextField:textField];直接代替[self performSelector:@selector(updateEmptyTextField :) withObject:textField afterDelay:0];? – 2011-01-31 14:13:54