2010-07-04 104 views
34

下面的代碼:目標C檢查是否文本字段爲空

- (IBAction) charlieInputText:(id)sender { 
    //getting value from text field when entered 
    charlieInputSelf = [sender stringValue]; 

    if (charlieInputSelf != @"") { 
     //(send field if not empty 
    } 
}  

這將是即使該字段爲空;因此,這不符合我的要求。

回答

80

簡單的檢查零,如果文本長度的長度大於0 - 不爲空

if (textField.text && textField.text.length > 0) 
{ 
    /* not empty - do something */ 
} 
else 
{ 
    /* what ever */ 
} 
+12

空我覺得堆棧已經變得比一個更有參考價值任何主要平臺的官方文檔 – ChuckKelly 2014-02-08 09:55:50

+2

其實如果textField是零,那麼textField.text.lenght == 0.所以你可以減少if: if(textField.text.lenght> 0)' – 2015-01-19 21:01:52

+0

這兩個條件是相互依賴的。只保留一個條件。因爲0&0 = 0,1&1 = 1 – Saranjith 2017-07-31 06:58:47

6

約書亞在狹窄的情況下,正確的答案,但通常使用你不能比較字符串對象==或!=運算符。您必須使用-isEqual:-isEqualToString:這是因爲charlieImputSelf@""實際上是指向對象的指針。雖然兩個字符序列可能相同,但它們不需要指向內存中的相同位置。

+3

所以如果你想檢查文本字段的值是否等於'Boo',你必須使用'if([textField.text isEqualToString: @「Boo」])''而不是'if(textField.text == @「Boo」)' – 2010-07-04 12:52:17

+0

是的(這很煩人,我不能只在這個文本框中輸入'yes') – JeremyP 2010-07-04 15:50:07

2

這些'工作'的方式。但是,我發現用戶可以用空格填充框。我發現使用正則表達式有助於(儘管我使用的是沒有空格的詞)我無法真正弄清楚如何讓空格。

NSError *error = NULL; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[ ]" options:NSRegularExpressionCaseInsensitive error:&error]; 

if (!([[inputField stringValue]isEqualTo:regex])) { 
     NSLog(@"Found a match"); 
// Do stuff in here // 
} 
49

我們已經有內置的方法返回布爾值,該布爾值指示文本輸入對象是否具有任何文本。

// In Obj-C 
if ([textField hasText]) { 
     //* Do Something you have text 
    }else{ 
     /* what ever */ 
    } 

// In Swift 

if textField.hasText { 
    //* Do Something you have text 
}else{ 
    /* what ever */ 
} 
+12

這應該是正確的)回答 – 2015-01-20 01:09:41

+0

我不知道hasText! – DogCoffee 2015-11-19 23:13:41

+0

let clientName = clientNameTF.hasText()? clientNameTF.text! :「客戶名稱」 – DogCoffee 2015-11-19 23:21:24

1

最efficent方式做,這是通過使用此

// set it into an NSString 
NSString *yourText = yourVariable.text; 

if([theText length] == 0]) 
{ 
// Your Code if it is equal to zero 
} 
else 
{ 
// of the field is not empty 

} 
1

檢查文本字段是否是斯威夫特

@IBOutlet weak var textField: NSTextField! 
    @IBOutlet weak var multiLineTextField: NSTextField! 

    @IBAction func textChanged(sender: AnyObject) { 
    //println("text changed! \(textField.stringValue)") 

    if textField.stringValue.isEmpty == false { 
     multiLineTextField.becomeFirstResponder() 
     multiLineTextField.editable = true 
    } else { 
     multiLineTextField.editable = false 
    } 
    }