views:

1136

answers:

4

I want to refer to the value of an empty text field because I want make an if function that if there is nothing in the UITextField the text of the UITextField will become "nothing".

+1  A: 

There is a better solution, but here is the check using an if-statement

if ([textField.text length] == 0) {
  // nothing
  textField.text = @"Nothing";
  // textField.backgroundColor = [UIColor greyColor]; // maybe play around with color
}

The better solution would be to use UITextfield's placeholder property, which does exactly as your question states: show a text if the UITextField is empty.

drvdijk
[textField.text length] will return 0 if the text property is nil, so you can actually get away with taking out the nil check.
Marc Charbonneau
I couldn't bear to see that either so I fixed it as I liked the rest of the answer quite a bit and thought this one should be primary.
Kendall Helmstetter Gelner
A: 
if( [[myUITextField text] length] == 0 )
{
     // do something here
}
alan
+6  A: 

Without having more context, I would say that the best way to go would be to set the placeholder property. Here's the information on that property from Apple's documentation:

@property(nonatomic, copy) NSString *placeholder

The string that is displayed when there is no other text in the text field. This value is nil by default. The placeholder string is drawn using a 70% grey color.

However, to answer your question directly, you can set the UITextField to a specific string (@"Nothing" in your case) when it's empty by using the following example:

if([myUITextField.text length] == 0) {
   myUITextField.text = @"Nothing";
}

More information on the UITextField class is available here.

Pierre-Luc Simard
The placeholder string property is definitely the way to go, unless you want to have the string "nothing" saved in your data model (usually it's preferable to just set it to nil though).
Marc Charbonneau
length is not a property of an NSString instance, it's an instance method.
drvdijk
Thanks to Marc for correcting me and drvdijk for correcting the correction ;-)
Pierre-Luc Simard
A: 

hey guys thanks a lot.. this was really helpful but i have one question... why the hell cant it simple work like if(textfield.text == nil) then textfield.text=@"NOTHING";

i mean what is so wrong with this isnt it logical..?

rakshak
This does not answer the question, so please post it as a separate question.
Peter Hosey