How to detect when UITextField become empty
I would like to perform a certain action when UITextField becomes empty (user deletes everything one sign after another or uses the clear option).
I thought about using two methods
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
and
- (BOOL)textFieldShouldClear:(UITextField *)textField;
from
UITextFieldDelegate
I'm not sure how to detect the situation when the text field becomes empty? I tried with:
if ([textField.text length] == 0)
but it does't work as the fisrt of the above methods is called before开发者_如何转开发 the sign is deleted from the text field.
Any ideas?
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSRange textFieldRange = NSMakeRange(0, [textField.text length]);
if (NSEqualRanges(range, textFieldRange) && [string length] == 0) {
// Game on: when you return YES from this, your field will be empty
}
return YES;
}
It's useful to note that the field won't be empty until after this method returns, so you might want to set some intermediate state here, then use textFieldDidEndEditing:
to know that the user is done emptying out the field.
If anyone who is searching Swift 4.2 version of this code is the following.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let textFieldRange = NSRange(location: 0, length: textField.text?.count ?? 0)
if NSEqualRanges(range, textFieldRange) && string.count == 0 {
// Do whatever you want when text field is empty.
}
return true
}
The following code works as well.
-(void)textfieldDidChange:(UITextField *)textField
{
if (textField == first)
{
[second becomeFirstResponder];
}
else if(textField == second)
{
if (textField.text.length == 0)
{
[first becomeFirstResponder];
}
else
{
[third becomeFirstResponder];
}
}
else if(textField == third)
{
if (textField.text.length == 0)
{
[second becomeFirstResponder];
}
else
{
[four becomeFirstResponder];
}
}
else if(textField == four)
{
if (textField.text.length == 0)
{
[third becomeFirstResponder];
}
else
{
[four becomeFirstResponder];
}
}
}
Added target for every textfield. For me I had to place cursor in previous field when text is empty the current textfield. Let me know if you need any clarity.
Here is a solution without using NSRange
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(textField.text.length==1 && string.length==0){
//textfield is empty
}else{
//textfield is not empty
}
return true;
}
精彩评论