Adding UITextFieldDelegate protocol.
@interface LoginViewController : UIViewController <UITextFieldDelegate>
Adding addGestureRecognizer for scrollview.
- (void)initTextField
{
// if you have a scrollview, you need set it.
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
tapGesture.cancelsTouchesInView = NO;
[self.layoutView addGestureRecognizer:tapGesture];
// set delegate
self.textFieldForEmail.delegate = self;
self.textFieldForPassword.delegate = self;
}
#pragma mark - textfield delgate
// hidden keyboard
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touchBegan:");
[self.view endEditing:YES];
[super touchesBegan:touches withEvent:event];
}
// clean init text
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
NSLog(@"shouldBeginEditing");
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
NSLog(@"shouldEndEditing");
return YES;
}
-(BOOL)textFieldShouldClear:(UITextField *)textField
{
NSLog(@"shouldClear");
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSLog(@"shouldReturn:%d",textField.tag);
// jump to next textfield
//[textField resignFirstResponder];
return YES;
}
// user input
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
return YES;
}
// method to hide keyboard when user taps on a scrollview
- (void)hideKeyboard
{
// [self.textFieldForUserName resignFirstResponder];
[self.view endEditing:YES];
}