【问题标题】:Get current keyboard frame gracefully?优雅地获取当前键盘框架?
【发布时间】:2015-07-22 05:24:39
【问题描述】:

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

【问题讨论】:

    标签: ios uiview keyboard inputview


    【解决方案1】:

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

    UIKeyboardWillChangeFrameNotification 
    UIKeyboardDidChangeFrameNotification 
    

    【讨论】:

    • 这些不会触发任何超过UIKeyboardDidShowNotification,除非firstResponder先辞职,然后重新激活,这是我希望在这里避免的。
    • 我刚刚测试过。这些通知对我有用。
    • 请在代码中详细说明。提醒您,我对未来的键盘框架更改不感兴趣(我知道该怎么做),只对调用时的现有框架不感兴趣。
    • 让我澄清一下。我不知道有任何 API 可以检查键盘框架大小。我们可以做的是观察键盘显示/隐藏/帧的变化,并在变化时将大小保存在变量中。这样我们总是知道键盘框架的大小。希望这很清楚。
    • 实际上,在应用程序的生命周期内监听这些通知的一些静态代码确实是最简单的解决方案。这使我可以在需要时优雅地查询 kbd 大小。我编辑了原始帖子的解决方案。
    猜你喜欢
    • 2010-11-19
    • 2012-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 2012-09-04
    • 1970-01-01
    • 2019-09-03
    相关资源
    最近更新 更多