How do I unfocus UITextFields when user presses other controls/blank space?
I always add this to my ViewController
override func viewDidLoad()
{
super.viewDidLoad()
// other stuff
// but to stop editing when the user taps anywhere on the view, add this gesture recogniser
let tapGestureBackground = UITapGestureRecognizer(target: self, action: #selector(self.backgroundTapped(_:)))
self.view.addGestureRecognizer(tapGestureBackground)
}
func backgroundTapped(_ sender: UITapGestureRecognizer)
{
self.endEditing(true)
}
SWIFT
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
Objective C
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
It will resign your textField or textView by tapping outside of it.
Note: It will not affect on scrollView
Scroll View
Objective C
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
tapGesture.cancelsTouchesInView = NO;
[yourScrollView/TableView addGestureRecognizer:tapGesture];
-(void)hideKeyboard {
[textFieldInYourScrollView/TableView resignFirstResponder];
}
SWIFT
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
tapGesture.cancelsTouchesInView = false
scrollView.addGestureRecognizer(tapGesture)
@objc func hideKeyboard() {
self.view.endEditing(true)
}
Hide Keyboard on Scrolling
scrollView.keyboardDismissMode = .onDrag
tableView.keyboardDismissMode = .onDrag
You can achieve this by using UIGestureRecognizerDelegate
.
Create UITapGestureRecognizer
object and add it to controller view. Write below code in viewDidLoad
method
- (void) viewDidLoad {
[super viewDidLoad];
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] init];
tapRecognizer.delegate = self;
[self.view addGestureRecognizer:tapRecognizer];
}
Don't forgot to extends your controller with UIGestureRecognizerDelegate
.
@interface YourViewController () <UIGestureRecognizerDelegate>
@property (nonatomic, weak) IBOutlet UITextField *textField;
@end
Now implement delegate method - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch;
its a delegate method of UITapGestureRecognizer
.
In this method you can simply check for your textField (in this example we have used self.textField
).
And write a condition to resignFirstResponder
of your textField.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if ([touch.view isEqual:self.textField]) {
return NO;
} else {
[self.textField resignFirstResponder];
return YES;
}
}