UIModalPresentationFormSheet模式下隐藏键盘


      在通常情况下,我们使用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 <UIKit/UIKit.h>


@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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值