如何以编程方式检查iOS应用程序中是否存在键盘?

我需要在我的iOS应用中检查键盘可见性的条件。


伪代码:


if(keyboardIsPresentOnWindow) {

    //Do action 1

}

else if (keyboardIsNotPresentOnWindow) {

    //Do action 2

}

如何检查这种情况?


BIG阳
浏览 508回答 3
3回答

LEATH

…或采取简单的方法:输入textField时,它成为第一响应者,并出现键盘。您可以使用来检查键盘的状态[myTextField isFirstResponder]。如果返回YES,则键盘处于活动状态。

函数式编程

drawonward的代码非常接近,但与UIKit的命名空间冲突,因此可以更易于使用。@interface KeyboardStateListener : NSObject {    BOOL _isVisible;}+ (KeyboardStateListener *)sharedInstance;@property (nonatomic, readonly, getter=isVisible) BOOL visible;@endstatic KeyboardStateListener *sharedInstance;@implementation KeyboardStateListener+ (KeyboardStateListener *)sharedInstance{    return sharedInstance;}+ (void)load{    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];    sharedInstance = [[self alloc] init];    [pool release];}- (BOOL)isVisible{    return _isVisible;}- (void)didShow{    _isVisible = YES;}- (void)didHide{    _isVisible = NO;}- (id)init{    if ((self = [super init])) {        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];        [center addObserver:self selector:@selector(didShow) name:UIKeyboardDidShowNotification object:nil];        [center addObserver:self selector:@selector(didHide) name:UIKeyboardWillHideNotification object:nil];    }    return self;}@end

繁花不似锦

UIKeyboardListener当您知道键盘不可见时,请创建一个,例如通过[UIKeyboardListener shared]从调用applicationDidFinishLaunching。@implementation UIKeyboardListener+ (UIKeyboardListener) shared {    static UIKeyboardListener sListener;        if ( nil == sListener ) sListener = [[UIKeyboardListener alloc] init];    return sListener;}-(id) init {    self = [super init];    if ( self ) {        NSNotificationCenter        *center = [NSNotificationCenter defaultCenter];        [center addObserver:self selector:@selector(noticeShowKeyboard:) name:UIKeyboardDidShowNotification object:nil];        [center addObserver:self selector:@selector(noticeHideKeyboard:) name:UIKeyboardWillHideNotification object:nil];    }    return self;}-(void) noticeShowKeyboard:(NSNotification *)inNotification {    _visible = true;}-(void) noticeHideKeyboard:(NSNotification *)inNotification {    _visible = false;}-(BOOL) isVisible {    return _visible;}@end
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

iOS