iOS应用中输入键盘隐藏

来源:互联网 发布:大数据论文3000字 编辑:程序博客网 时间:2024/06/05 21:06

      在通常情况下,我们使用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方法失效的问题。


原创粉丝点击