Reputation: 153
I can't figure out how to dissmis keyboard when Done or something outside textfield is touched. Here is what I try
myController.h
@interface myController : UIViewController <UITextFieldDelegate>{
secondViewController *secondView;
}
myController.m
-(void)loadView
{
.....
textFieldRounded.borderStyle = UITextBorderStyleRoundedRect;
textFieldRounded.textColor = [UIColor blackColor];
textFieldRounded.font = [UIFont systemFontOfSize:17.0];
textFieldRounded.placeholder = @"<enter text>";
textFieldRounded.backgroundColor = [UIColor whiteColor];
textFieldRounded.autocorrectionType = UITextAutocorrectionTypeNo;
textFieldRounded.keyboardType = UIKeyboardTypeDefault;
textFieldRounded.returnKeyType = UIReturnKeyDone;
textFieldRounded.clearButtonMode = UITextFieldViewModeWhileEditing;
[textFieldRounded.delegate = self;
[self.view addSubview:textFieldRounded];
....
}
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
return [textField resignFirstResponder];
}
Upvotes: 0
Views: 882
Reputation: 6413
To make keyboard hidden by tap outside textfield, you can use gesture recognizer as shown below
- (void)viewDidLoad
{
// don't forget to assign textField delegate, after textField is created
textFieldRounded.delegate = self;
//...
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
tapRecognizer.numberOfTouchesRequired = 1;
[self.view addGestureRecognizer:tapRecognizer];
[tapRecognizer release]
}
- (void)singleTap:(id)sender
{
// if you have multiple text fields use this line:
[self.view endEditing:NO];
}
// remove resigning call from textField delegate
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
return YES;
}
// on Done/Return button handling use this
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
Upvotes: 0
Reputation: 20410
Use:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
To capture when you touch outside of the textfield
Upvotes: 1