Skip to content

Instantly share code, notes, and snippets.

@justin
Created April 3, 2012 02:20
Show Gist options
  • Save justin/2288837 to your computer and use it in GitHub Desktop.
Save justin/2288837 to your computer and use it in GitHub Desktop.
Handle delete in empty UITextField
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if ([textField.text length] == 0)
{
textField.text = DSEmptyNewLineCharacter;
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// The delete key being pressed always has an NSRange length of one.
BOOL isDeleteKey = (range.length == 1);
BOOL isDeletingTheFirstCharacter = (range.location == 0) && (range.length == 1) && (isDeleteKey == YES);
BOOL firstFieldHasFocus = [textField isEqual:self.firstField];
if (firstFieldHasFocus == YES)
{
if (isDeletingTheFirstCharacter == YES)
{
BOOL fieldHasOnlyEmptyLine = [self.firstField.text isEqual:DSEmptyNewLineCharacter];
if (fieldHasOnlyEmptyLine == YES)
{
[self.firstField resignFirstResponder];
return NO;
}
else
{
self.firstField.text = DSEmptyNewLineCharacter;
return NO;
}
}
[self stripNewLineCharacterIfNecessaryFromField:self.firstField];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment