Form Sheet的ViewController无法自动隐藏键盘的解决方法

来源:互联网 发布:apache https 编辑:程序博客网 时间:2024/05/17 04:13

Form Sheet的ViewController无法自动隐藏键盘的解决方法

 

在实现登录,注册等iPad界面时,经常要用到FormSheet形式的ViewController。最简单的比如说登录界面,有用户名,密码,登录按钮组成,即两个UITextField,一个UIButton组成,希望输入用户名,按键盘的return键时,跳到输入密码,输入密码后按键盘的return键,键盘消失,进入登录处理。在非FormSheet形式的时候,界面处理跟预期一致。但当是FormSheet形式的时候,键盘隐藏不了。代码如下

 

1、第一个ViewController有一个按钮,弹出一个FormSheet风格的视图(部分代码)。

- (IBAction)buttonPressed:(id)sender {

   

    DemoViewController *demoViewController = [[DemoViewControlleralloc] initWithNibName:@"DemoViewController" bundle: nil];

    UINavigationController *nav = [[[UINavigationControlleralloc] initWithRootViewController: demoViewController]autorelease];

    nav.modalPresentationStyle =UIModalPresentationFormSheet;

    [demoViewController release];

   

    [selfpresentViewController: nav animated: YES completion: nil];   

  

}

 

2、弹出的视图代码(部分代码):

- (void)viewDidLoad

{

    [superviewDidLoad];

    // Do anyadditional setup after loading the view from its nib.

   

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItemalloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDonetarget:self action:@selector(done)] autorelease];

   

    _tfName .delegate =self;

    _tfPassword.delegate =self;

}

 

- (void)done{

   

    [selfdismissViewControllerAnimated: YES completion: nil];

}

 

 

-(BOOL)textFieldShouldReturn:(UITextField *)textField{

   

    if (textField ==_tfName) {

        [_tfPasswordbecomeFirstResponder];

        returnYES;

    }

   

    [textField resignFirstResponder];  

   

   

    returnYES;

}

 

- (IBAction)buttonLoginPressed:(id)sender {

   

    [_tfNameresignFirstResponder];

    [_tfPasswordresignFirstResponder];

}

 

 

在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>

 

@interfaceUINavigationController(KeyboardDismiss)

 

-(BOOL)disablesAutomaticKeyboardDismissal;

 

@end

File:UINavigationController+KeyboardDismiss.m

#import "UINavigationController+KeyboardDismiss.h"

 

@implementationUINavigationController(KeyboardDismiss)

 

-(BOOL)disablesAutomaticKeyboardDismissal

{

    returnNO;

}

 

@end

Do not forget to import the category in the file where you use theUINavigationController.

 

 

将上面的类别方法放在使用UINavigationController的地方就可以了。