How do I dismiss the keyboard in the MFMailComposeViewController when the user hits the return key?
There is no way to change the behavior of an MFMailComposeViewController
(edit: by that I mean using only public APIs in such a way that your app won't be rejected by Apple -- there is very probably a way to do this "illegally" if you're building an in-house app).
Quote: "Important: The mail composition interface itself is not customizable and must not be modified by your application."
It's in line with Apple's HIG to always provide a single, consistent behavior for sending mail.
I believe the following solution I've just developed does not modify or damage the reliable user experience in the mail view controller—it merely enhances it for those who want to dismiss the keyboard. I do not change the functionality of existing elements, I only add a new element. The part of the code that gets the height of the keyboard after it is shown comes from this answer. Here goes:
- (IBAction)showMailController {
//Present mail controller on press of a button, set up notification of keyboard showing and hiding
[nc addObserver:self selector:@selector(keyboardWillShow:) name: UIKeyboardWillShowNotification object:nil];
[nc addObserver:self selector:@selector(keyboardWillHide:) name: UIKeyboardWillHideNotification object:nil];
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
//... and so on
}
- (void)keyboardWillShow:(NSNotification *)note {
//Get view that's controlling the keyboard
UIWindow* keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView* firstResponder = [keyWindow performSelector:@selector(firstResponder)];
//set up dimensions of dismiss keyboard button and animate it into view, parameters are based on landscape orientation, the keyboard's dimensions and this button's specific dimensions
CGRect t;
[[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &t];
button.frame = CGRectMake(324,(290-t.size.height),156,37);
button.alpha = 0.0;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0];
[[[[[firstResponder superview] superview] superview] superview] addSubview:button];
button.alpha = 1.0;
button.frame = CGRectMake(324,(253-t.size.height),156,37);
[UIView commitAnimations];
}
- (IBAction)dismissKeyboardInMailView {
//this is what gets called when the dismiss keyboard button is pressed
UIWindow* keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView* firstResponder = [keyWindow performSelector:@selector(firstResponder)];
[firstResponder resignFirstResponder];
}
- (void)keyboardWillHide:(NSNotification *)note {
//hide button here
[button removeFromSuperview];
}