KWKeyboardListener 1.0

KWKeyboardListener 1.0

测试已测试
语言语言 Obj-CObjective C
许可证 自定义
发布时间最后发布2014年12月

Florent Crivello维护。



  • Florent Crivello

轻松创建一个能够响应用户键盘事件的类。

注册一个新的监听器

之前

- (void)registerMyClass {
   NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
   [defaultCenter addObserver:self selector:@selector(didShow:) name:UIKeyboardDidShowNotification object:nil];
   [defaultCenter addObserver:self selector:@selector(didHide:) name:UIKeyboardDidHideNotification object:nil];
   [defaultCenter addObserver:self selector:@selector(willShow:) name:UIKeyboardWillShowNotification object:nil];
   [defaultCenter addObserver:self selector:@selector(willHide:) name:UIKeyboardWillHideNotification object:nil];
   [defaultCenter addObserver:self selector:@selector(didChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
   [defaultCenter addObserver:self selector:@selector(willChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

// No autocompletion here, you have to type the methods' name…
- (void)didShow:(NSNotification *)notification {
...
}

- (void)willShow:(NSNotification *)notification {
...
}

- (void)didHide:(NSNotification *)notification {
...
}

- (void)willHide:(NSNotification *)notification {
...
}

- (void)didChangeFrame:(NSNotification *)notification {
...
}

- (void)willChangeFrame:(NSNotification *)notification {
...
}

之后

- (void)registerMyClass {
  [[KWKeyboardListener sharedInstance] addKeyboardEventsListener:self withHandler:^(CGRect keyboardFrame, BOOL opening, BOOL closing) {
      // This block will get called when the keyboard *will* show/hide/change frame
  }];
}

您也可以让您的类遵循 KWKeyboardEventsListener 协议,调用 [[KWKeyboardListener sharedInstance] addKeyboardEventsListener:self] 并实现您希望的方法。这种方法与 NSNotificationCenter 相比的优势在于,您不需要为每个希望响应的事件分别注册您的类,而且由于协议的存在,通过自动完成功能,您只需简单开始输入 - (void)keyboard 并查看支持的事件列表,这些事件有:

- (void)keyboardWillShowWithInfos:(NSDictionary *)infos;
- (void)keyboardWillHideWithInfos:(NSDictionary *)infos;
- (void)keyboardDidShowWithInfos:(NSDictionary *)infos;
- (void)keyboardDidHideWithInfos:(NSDictionary *)infos;
- (void)keyboardWillChangeFrameWithInfos:(NSDictionary *)infos;
- (void)keyboardDidChangeFrameWithInfos:(NSDictionary *)infos;

信息只是您通常会从常规 NSNotification 收到的 userInfo。您可以使用常规通知键获取事件的相关信息,如 UIKit 中定义的。

UIKIT_EXTERN NSString *const UIKeyboardFrameBeginUserInfoKey        NS_AVAILABLE_IOS(3_2); // NSValue of CGRect
UIKIT_EXTERN NSString *const UIKeyboardFrameEndUserInfoKey          NS_AVAILABLE_IOS(3_2); // NSValue of CGRect
UIKIT_EXTERN NSString *const UIKeyboardAnimationDurationUserInfoKey NS_AVAILABLE_IOS(3_0); // NSNumber of double
UIKIT_EXTERN NSString *const UIKeyboardAnimationCurveUserInfoKey    NS_AVAILABLE_IOS(3_0); // NSNumber of NSUInteger 

了解键盘状态

此外,KWKeyboardListener 单例在类加载时实例化,因此您无需做任何事情,这可以让您从任何地方获取应用中键盘的当前状态,使用其 keyboardVisible 布尔属性。

Pod

pod 'KWKeyboardListener', '~>1.0'