0

I have a textField called titleTextField in which the user can enter the title of their choice before saving a note. What I want to do is automatically fill this field with the text "Untitled" if the user has left this field blank.

I've tried several solutions, but they either do nothing or set the title always to Untitled even if the user has entered text.

This is the closest I've gotten, but it's still not working right:

    if(![self.titleTextField.text isEqual:@""]){
    self.titleTextField.text = @"Untitled";
}

My thought was that this would check whether the titleTextField is empty, and if so, it would populate the field with the text "Untitled." I've tried applying this in the viewDidLoad, viewWillAppear, and viewWillDisappear -- I really don't care whether the "Untitled" text is populated when the screen loads or after the user is finished with the page; I just want the end result to be an empty title field saving with the text "Untitled".

Is the coding wrong, or am I just applying it in the wrong place?

1
  • 1
    Your code is setting the text field to Untitled if the current text is not empty. Commented Aug 16, 2017 at 3:42

1 Answer 1

1

Solution as per the way you are looking for is :

if([self.titleTextField.text isEqualToString:@""]){
    self.titleTextField.text = @"Untitled";
}

You can also use below :

if([self.titleTextField.text length] == 0){
    self.titleTextField.text = @"Untitled";
}
Sign up to request clarification or add additional context in comments.

3 Comments

isEqual: will work just as well as isEqualToString:.
Thank you! The second one (with the length parameter) worked like a charm!
The 2nd option has the advantage that it works even if self.titleTextField.text is nil.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.