Is there any way to detect when the backspace/delete key is pressed in the iPhone keyboard on a UITextField that is empty?
Here is non-hacky and very simple with a quick subclass of UITextField.
This is the best solution. Objective C is based on sub classing and this solution uses it properly to solve the problem.
Sadly, this only works for >= iOS 6 though
//Header
//MyTextField.h
//create delegate protocol
@protocol MyTextFieldDelegate <NSObject>
@optional
- (void)textFieldDidDelete;
@end
@interface MyTextField : UITextField<UIKeyInput>
//create "myDelegate"
@property (nonatomic, assign) id<MyTextFieldDelegate> myDelegate;
@end
//Implementation
#import "MyTextField.h"
@implementation MyTextField
- (void)deleteBackward {
[super deleteBackward];
if ([_myDelegate respondsToSelector:@selector(textFieldDidDelete)]) [_myDelegate textFieldDidDelete];
}
@end
//View Controller Header
#import "MyTextField.h"
//add "MyTextFieldDelegate" to you view controller
@interface ViewController : UIViewController <MyTextFieldDelegate>
@end
Now simply add "MyTextFieldDelegate" to your ViewController and set your textfields "myDelegate" to "self":
//View Controller Implementation
- (void)viewDidLoad {
//initialize your text field
MyTextField *input = [[MyTextField alloc] initWithFrame:CGRectMake(0, 0, 70, 30)];
//set your view controller as "myDelegate"
input.myDelegate = self;
//add your text field to the view
[self.view addSubview:input];
}
//MyTextField Delegate
- (void)textFieldDidDelete {
NSLog(@"delete");
}