Reputation: 11904
This is my custom UITextField class:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.delegate = self;
[self addTarget:self action:@selector(hideKeyboard) forControlEvents:UIControlEventTouchUpOutside];
}
return self;
}
- (void) hideKeyboard
{
NSLog(@"Clicked outside");
[self resignFirstResponder];
}
However, when I click outside of the text field, hideKeyboard
never gets called. Can anyone explain why and how should I fix this?
Upvotes: 0
Views: 76
Reputation: 9567
Your touches could be swallowed by some other UIControl that is consuming them. Without seeing your hierarchy it's impossible to tell.
However, I wouldn't suggest this even if you just had 1 UITextField on a blank UIView; it doesn't scale well, and could lead to strange bugs later if you add another UIControl to the view. What happens if you have this TextField and a UIButton in the same UIView?
Rather, I'd change the superview to be a UIControl (subclass of UIView), and just use UIControlEventTouchUpInside to trigger a method that dismisses the keyboard.
Upvotes: 0
Reputation: 318774
The event you registered for will only happen if you begin the touch inside the text field and finish the touch outside of the text field.
If you start the touch outside the text field, the text field does not get any event.
Add a touch gesture recognizer to the view that contains the text field. When that event is triggered, resign the current first responder.
Upvotes: 2