是否有一种优雅的方式来获取当前可见的任何 inputView 的框架(大小)?优雅,我的意思是不辞职,然后重新激活第一响应者,因为这会丢弃任何 kbd 状态数据,例如 Shift 键状态。
我目前做的是这样的:
- (CGSize)inputViewSize
{
__block CGSize result = CGSizeZero;
UIResponder *firstResponder = [self getFirstResponder];
id observer = [NSNotificationCenter.defaultCenter addObserverForName:UIKeyboardDidShowNotification object:nil queue:nil usingBlock:^(NSNotification *note)
{
result = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
}];
[firstResponder resignFirstResponder];
[firstResponder becomeFirstResponder];
[NSNotificationCenter.defaultCenter removeObserver:observer];
return result;
}
编辑:我应该做的是:
@implementation UIApplication (KeyboardFrame)
static CGRect _keyboardFrame = (CGRect){ (CGPoint){ 0.0f, 0.0f }, (CGSize) { 0.0f, 0.0f } };
+ (CGSize)keyboardSize { return _keyboardFrame.size; }
+ (void)load
{
[NSNotificationCenter.defaultCenter addObserverForName:UIKeyboardDidShowNotification object:nil queue:nil usingBlock:^(NSNotification *note)
{
_keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
}];
[NSNotificationCenter.defaultCenter addObserverForName:UIKeyboardDidChangeFrameNotification object:nil queue:nil usingBlock:^(NSNotification *note)
{
_keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
}];
[NSNotificationCenter.defaultCenter addObserverForName:UIKeyboardDidHideNotification object:nil queue:nil usingBlock:^(NSNotification *note)
{
_keyboardFrame = CGRectZero;
}];
}
@end