0

是否有一种优雅的方式来获取当前可见的任何 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
4

1 回答 1

0

您需要观察键盘通知。如果对键盘框架更改感兴趣,您可以利用以下两个通知:

UIKeyboardWillChangeFrameNotification 
UIKeyboardDidChangeFrameNotification 
于 2015-05-12T16:04:40.670 回答