user3331589
user3331589

Reputation: 71

How to erase or clear UITextField?

How can I make a text field box remove all content on the user's first keypress?

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

    if([tfieldDOB.text length] == 4)
    {
        tfieldDOB.text=[NSString stringWithFormat:@"%@/",tfieldDOB.text];
    }
    else if([tfieldDOB.text length]==7)
    {
        tfieldDOB.text=[NSString stringWithFormat:@"%@/",tfieldDOB.text];
        
    }
    
    return YES;
}

Upvotes: 7

Views: 27601

Answers (2)

Anbu.Karthik
Anbu.Karthik

Reputation: 82759

change the textfield attribute clear button mode in appears while editing

or other choice just use the single line, where you need to add

yourtextfieldname.text=@"";  //it is used for clear the textfield values 

Swift

yourtextfieldname.text=""

or another way

 clearField =@"YES";

if([clearField isequaltostring:@"YES"])  //check this line in 
{
    tfieldDOB.text = @"";
    clearField =@"NO";
}

Upvotes: 12

Zen
Zen

Reputation: 3117

Implement the text field's delegate method textFieldShouldBeginEditing: and set the text as empty string when the text field is just about to being editing.

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [textField setText:@""];
    return YES;
}

Or you can set the property clearsOnBeginEditing of the textfield as

[textField setClearsOnBeginEditing:YES];

and it will clear the text when editing begins

Upvotes: 5

Related Questions