[ios] iOS 앱에 키보드가 있는지 프로그래밍 방식으로 어떻게 확인할 수 있습니까?

iOS 앱에서 키보드 가시성 상태를 확인해야합니다.

의사 코드 :

if(keyboardIsPresentOnWindow) {
    //Do action 1
}
else if (keyboardIsNotPresentOnWindow) {
    //Do action 2
}

이 상태를 어떻게 확인할 수 있습니까?



답변

… 또는 쉬운 방법을 선택하십시오.

textField를 입력하면 첫 번째 응답자가 되고 키보드가 나타납니다. 로 키보드의 상태를 확인할 수 있습니다 [myTextField isFirstResponder]. 를 반환 YES하면 키보드가 활성화 된 것입니다.


답변

drawnonward의 코드는 매우 가깝지만 UIKit의 네임 스페이스와 충돌하여 사용하기 쉽게 만들 수 있습니다.

@interface KeyboardStateListener : NSObject {
    BOOL _isVisible;
}
+ (KeyboardStateListener *)sharedInstance;
@property (nonatomic, readonly, getter=isVisible) BOOL visible;
@end

static 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


답변

키보드에 대해 제공되는 알림을 사용해야한다고 생각합니다.

출처 : http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UITextField_Class/Reference/UITextField.html

키보드 알림

시스템이 키보드를 표시하거나 숨기면 여러 키보드 알림을 게시합니다. 이러한 알림에는보기 이동과 관련된 계산에 사용할 수있는 키보드 크기 등의 정보가 포함됩니다. 이러한 알림을 등록하는 것은 키보드에 대한 일부 유형의 정보를 얻을 수있는 유일한 방법입니다. 시스템은 키보드 관련 이벤트에 대해 다음 알림을 제공합니다.

* UIKeyboardWillShowNotification
* UIKeyboardDidShowNotification
* UIKeyboardWillHideNotification
* UIKeyboardDidHideNotification

이러한 알림에 대한 자세한 내용은 UIWindow Class Reference에서 해당 설명을 참조하십시오. 키보드를 표시하고 숨기는 방법에 대한 정보는 텍스트 및 웹을 참조하십시오.


답변

Swift 3 구현

    import Foundation
class KeyboardStateListener: NSObject
{
    static let shared = KeyboardStateListener()
    var isVisible = false

    func start() {
        NotificationCenter.default.addObserver(self, selector: #selector(didShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(didHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func didShow()
    {
        isVisible = true
    }

    func didHide()
    {
        isVisible = false
    }
}


답변

키보드 표시에 대한 표시로 창 하위보기 계층 구조를 사용하는 것은 해킹입니다. Apple이 기본 구현을 변경하면 이러한 모든 답변이 깨질 것입니다.

올바른 방법은 키보드 표시를 모니터링하고 App Delegate 내부와 같이 알림 애플리케이션 전체를 숨기는 것입니다.

AppDelegate.h에서 :

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (assign, nonatomic) BOOL keyboardIsShowing;

@end

AppDelegate.m에서 :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // Monitor keyboard status application wide
    self.keyboardIsShowing = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)
                                             name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:)
                                             name:UIKeyboardWillHideNotification object:nil];

    return YES;
}

- (void)keyboardWillShow:(NSNotification*)aNotification
{
    self.keyboardIsShowing = YES;
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    self.keyboardIsShowing = NO;
}

그런 다음 다음을 사용하여 확인할 수 있습니다.

BOOL keyboardIsShowing = ((AppDelegate*)[UIApplication sharedApplication].delegate).keyboardIsShowing;

사용자가 블루투스 또는 외부 키보드를 사용하는 경우 키보드 표시 / 숨기기 알림이 실행되지 않습니다.


답변

확장 추가

extension UIApplication {
    /// Checks if view hierarchy of application contains `UIRemoteKeyboardWindow` if it does, keyboard is presented
    var isKeyboardPresented: Bool {
        if let keyboardWindowClass = NSClassFromString("UIRemoteKeyboardWindow"),
            self.windows.contains(where: { $0.isKind(of: keyboardWindowClass) }) {
            return true
        } else {
            return false
        }
    }
}

그런 다음 키보드가 있는지 확인하십시오.

if UIApplication.shared.isKeyboardPresented {
     print("Keyboard presented")
} else {
     print("Keyboard is not presented")
}