Form Sheet的ViewController无法自动隐藏键盘的解决方法
在实现登录,注册等iPad界面时,经常要用到FormSheet形式的ViewController。最简单的比如说登录界面,有用户名,密码,登录按钮组成,即两个UITextField,一个UIButton组成,希望输入用户名,按键盘的return键时,跳到输入密码,输入密码后按键盘的return键,键盘消失,进入登录处理。在非FormSheet形式的时候,界面处理跟预期一致。但当是FormSheet形式的时候,键盘隐藏不了。代码如下
1、第一个ViewController有一个按钮,弹出一个FormSheet风格的视图(部分代码)。
- (IBAction)buttonPressed:(id)sender {
DemoViewController *demoViewController = [[DemoViewController alloc] initWithNibName: @"DemoViewController" bundle: nil];
UINavigationController *nav = [[[UINavigationController alloc] initWithRootViewController: demoViewController] autorelease];
nav.modalPresentationStyle = UIModalPresentationFormSheet;
[demoViewController release];
[self presentViewController: nav animated: YES completion: nil];
}
2、弹出的视图代码(部分代码):
- (void)viewDidLoad
{
[super viewDidLoad];
// Do anyadditional setup after loading the view from its nib.
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done)] autorelease];
_tfName .delegate = self;
_tfPassword.delegate = self;
}
- (void)done{
[self dismissViewControllerAnimated: YES completion: nil];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
if (textField == _tfName) {
[_tfPassword becomeFirstResponder];
return YES;
}
[textField resignFirstResponder];
return YES;
}
- (IBAction)buttonLoginPressed:(id)sender {
[_tfName resignFirstResponder];
[_tfPassword resignFirstResponder];
}
在http://stackoverflow.com/questions/3372333/ipad-keyboard-will-not-dismiss-if-modal-view-controller-presentation-style-is-ui
上找到了解决方法:
Be careful ifyou are displaying the modal with a UINavigationController. You then haveto set the disablesAutomaticKeyboardDismissal on thenavigation controller and not on the view controller. You can easily do thiswith categories.
File:UINavigationController+KeyboardDismiss.h
#import <Foundation/Foundation.h>
@interface UINavigationController(KeyboardDismiss)
-(BOOL)disablesAutomaticKeyboardDismissal;
@end
File:UINavigationController+KeyboardDismiss.m
#import "UINavigationController+KeyboardDismiss.h"
@implementation UINavigationController(KeyboardDismiss)
-(BOOL)disablesAutomaticKeyboardDismissal
{
returnNO;
}
@end
Do not forget to import the category in the file where you use theUINavigationController.
将上面的类别方法放在使用UINavigationController的地方就可以了。