unchainedprey
unchainedprey

Reputation: 11

Setting custom text if TextField is empty

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?

Upvotes: 0

Views: 153

Answers (1)

Hooda
Hooda

Reputation: 1187

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";
}

Upvotes: 1

Related Questions