---
title: "UIModalPresentationFormSheet模式下隐藏键盘"
author: "啸笑天"
date: "2016-03-05T10:13:24Z"
tags: []
categories: ["移动开发"]
slug: "uimodalpresentationformsheet"
draft: false
lastmod: "2016-03-05T10:16:45Z"
id: 2280745
url: "https://justsee.iteye.com/blog/2280745"
---

在通常情况下，我们使用UITextField空间来完成输入，点击编辑区域，键盘自动出现，点击Done按钮，键盘自动消失。如果用代码来控制，则是使用becomeFirstResponder和resignFirstResponder来控制键盘的出现/隐藏。

      不过如果你在UIModalPresentationFormSheet这种风格的弹出界面时，resignFirstResponder是无法自动隐藏键盘的。

      笔者在遇到这个问题时也为此困惑了不少时候，查阅了不少资料，最后发现之所以在UIModalPresentationFormSheet下的视图无法用resignFirstResponder这个API，是因为在进入到此模式的后，系统将disablesAutomaticKeyboardDismissal方法返回值置为了YES。  
官方文档上说“The default implementation of this method returns YES when the modal presentation style of the view controller is set to UIModalPresentationFormSheet and returns NO for other presentation styles.”翻译成中文意思是“这个方法在UIModalPresentationFormSheet时默认值是YES，在其他情况下默认值是NO”。

      如果应用一定需要隐藏键盘，解决方法有两个：

1\. 调用Apple的Private API  
    @try  
      
    {  
          
        Class UIKeyboardImpl = NSClassFromString(@"UIKeyboardImpl");  
          
        id activeInstance = \[UIKeyboardImpl performSelector:@selector(activeInstance)];  
          
        \[activeInstance performSelector:@selector(dismissKeyboard)];  
          
    }  
      
    @catch (NSException \*exception)  
      
    {  
          
        NSLog(@"Exception : %@", exception);  
          
    }  
这方法实现简单，只是由于调用了Apple的Private API，可以工作，但无法通过APP Store的审核

 

2\. 重新实现disablesAutomaticKeyboardDismissal  
如果直接使用ViewController则可以在实现文件中重新实现这个API，将返回值改为NO后，即可正常使用resignFirstResponsder方法隐藏键盘  
\- (BOOL)disablesAutomaticKeyboardDismissal  
{  
    return NO;  
}// disablesAutomaticKeyboardDismissal

但很多时候我们是把ViewController放在UINavigationController中的，这种情况下直接在ViewController里面实现disablesAutomaticKeyboardDismissal依然失效，而应该在UINavigationController中实现这个API。

#import &lt;UIKit/UIKit.h&gt;

@interface UINavigationController (UINavigationController\_KeyboardDismiss)

\- (BOOL)disablesAutomaticKeyboardDismissal;

@end

#import "UINavigationController\_UINavigationController\_KeyboardDismiss.h"

@implementation UINavigationController (UINavigationController\_KeyboardDismiss)

\- (BOOL)disablesAutomaticKeyboardDismissal  
{  
    return NO;  
}// disablesAutomaticKeyboardDismissal

@end

经过UINavigationController Category对disablesAutomaticKeyboardDismissal方法的重写后，即可解决resignFirstResponder方法失效的问题。

 

thx：

http://blog.csdn.net/sakulafly/article/details/9081107

http://stackoverflow.com/questions/3372333/ipad-keyboard-will-not-dismiss-if-modal-viewcontroller-presentation-style-is-uim/3386768#3386768

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController\_Class/index.html