1) When clicking ‘Done’
Put protocol UITextViewDelegate and/or UITextFieldDelegate in there…
1 2 3 4 |
@interface RegistrationViewController : UIViewController < UITextViewDelegate, UITextFieldDelegate > |
set up the variable….make sure you add target for the method UIControlEventEditingDidEndOnExit:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//insert uitextfield UITextField * nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(10.0f, 128.0f, 300.0f, 64.0f)]; nameTextField.tag = UITEXTFIELD_NAME; [nameTextField setText:@"test"]; nameTextField.borderStyle = UITextBorderStyleRoundedRect; nameTextField.textColor = [UIColor blackColor]; nameTextField.delegate = self; [nameTextField addTarget:self action:@selector(textFieldDoneEditing:) forControlEvents:UIControlEventEditingDidEndOnExit ]; nameTextField.font = [UIFont systemFontOfSize:20.0 ]; nameTextField.autocorrectionType = UITextAutocorrectionTypeNo; nameTextField.keyboardType = UIKeyboardTypeDefault; nameTextField.returnKeyType = UIReturnKeyDone; nameTextField.clearButtonMode = UITextFieldViewModeWhileEditing; [self.view addSubview:nameTextField]; [nameTextField release]; |
Implement the method:
1 2 3 4 5 6 7 |
#pragma mark - responds to Done button pushed on keyboard - (BOOL)textFieldDoneEditing:(UITextField *)textField { DLOG(@"textFieldDoneEditing"); [textField resignFirstResponder]; return YES; } |
2) To dismiss Keyboard on tap of the View:
view controller’s header:
1 |
@property (nonatomic, assign) id currentResponder; |
view controller’s viewDidLoad:
1 2 3 4 5 6 |
//add tap gesture recognizer for our self.view UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignOnTap:)]; [singleTap setNumberOfTapsRequired:1]; [singleTap setNumberOfTouchesRequired:1]; [self.view addGestureRecognizer:singleTap]; [singleTap release]; |
view controller:
1 2 3 4 5 |
//our responder takes on whatever textfield is being edited - (void)textFieldDidBeginEditing:(UITextField *)textField { DLOG(@"textFieldDidBeginEditing"); self.currentResponder = textField; } |
Finally, follow this link http://rickytsao.com/?p=1299
in order to cancel keyboard by tapping anywhere outside of it.