问题
I have a table with UITextFields, and I want to make it so that when a textfield is selected, the current info is cleared (to allow new input), but if the user decides (after selecting) that they don't want to change it, I want them to be able to click elsewhere and the data from before reappears in the textfield.
Is there an easy way to do this?
回答1:
A good way to do this that's nice and user friendly is to use the placeholder
property. Set up your viewController as the textfield's delegate (as described by Andeh) then add the following code:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
textField.placeholder = textField.text;
textField.text = @"";
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
if (textField.text.length == 0) {
textField.text = textField.placeholder;
}
textField.placeholder = @"";
}
And you're done. If you have multiple UITextField
s on the page and you don't want this behaviour for all of them you can add a check to the methods above.
回答2:
In the textFieldDidBeginEditing
delegate method, save the current value to a persisting variable before clearing the UITextField. Then in the didFinishEditing
delegate method, if the new length of the user input is 0 set the text back to the stored value!
UITextField Delegate docs for reference.
回答3:
First I think you have two sets of behaviors here.
- The text field must clear the value when you begin editing. This exists:
-clearsOnBeginEditing
. - The text field must restore the previous text if text is empty. Subclassing seems the better solution.
Here is a possible sample class:
// MyRestoringTextField.h
@interface MyRestoringTextField : UITextField
@end
// MyTextField.m
@interface MyRestoringTextField ()
@property (strong, nonatomic) NSString *previousText;
@end
@implementation MyRestoringTextField
- (BOOL)becomeFirstResponder
{
BOOL result = [super becomeFirstResponder];
self.previousText = self.text;
return result;
}
- (BOOL)resignFirstResponder
{
BOOL result = [super resignFirstResponder];
if (self.text.length == 0)
self.text = self.previousText;
return result;
}
@end
Hope that helps.
回答4:
To clear and then restore a textField if you fail to make an entry, use the following delegates as such:
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
[[NSUserDefaults standardUserDefaults] setObject:textField.text forKey:kTextFieldIdentifier];
textField.text = @"";
}
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
if ([textField.text isEqualToString:@""])
textField.text = [[NSUserDefaults standardUserDefaults]
stringForKey:kTextFieldIdentifier];
return YES;
}
回答5:
As of iOS 8.1
, textFieldDidBeginEditing
is already receiving a cleared text. You should use
-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField
to initialized the placeholder field.
来源:https://stackoverflow.com/questions/12169145/uitextfield-clear-when-selected-but-also-restore-data-if-nothing-is-input