In Xcode4 I\'ve created some placeholder text for a UITextField and I\'d like it to clear when the user taps in the box.
So, in the Attributes Inspector for the text fie
make your ViewController the delegate of the textField and implement those two methods:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
textField.placeholder = nil;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
textField.placeholder = @"Your Placeholdertext";
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
textField.placeholder=nil;
}
textfield delegate make place holder value to nil
The solution provided by Matthias Bauch works well, but what happens when you have more than one UITextField
to worry about? Now you have to identify which UITextField
is referred to in textFieldDidEndEditing:textField
(possibly by use of the tag property), and that results in more unnecessary code and logic.
A much simpler solution: simply assign a clear color to the placeholder text , and when done editing, revert back to it's original color. This way, your textFieldDidEndEditing:textField
doesn't have to identify the textField
to set back its corresponding text after it was nullified as in Bauch's solution.
- (void)textFieldDidBeginEditing:(UITextField *)textField {
[textField setValue:[UIColor clearColor] forKeyPath:@"_placeholderLabel.textColor"];
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
[textField setValue:[UIColor placeholderColor] forKeyPath:@"_placeholderLabel.textColor"];
}
On Button action Event put this Code:
txtName.placeholder = @"";
In your .h file declare a function like
-(IBAction)clear:(id)sender;
attach this function to your touchdown event of your UITextField
.
in your .m file
-(IBAction)clear:(id)sender
{
myplaceHolderText.text=@"";
}
In case of SWIFT 3 or later
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.placeholder = nil
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.placeholder = "Text Placeholder"
}