【问题标题】:Deprecated constant in iOSiOS 中不推荐使用的常量
【发布时间】:2010-07-02 01:41:54
【问题描述】:

我构建了一个针对 iOS 3.1.3 及更高版本的应用程序,但遇到了UIKeyboardBoundsUserInfoKey 的问题。事实证明它在 iOS 3.2 及更高版本中已被弃用。我所做的是使用以下代码根据 iOS 版本使用正确的键:

if ([[[UIDevice currentDevice] systemVersion] compare:@"3.2" options:NSNumericSearch] != NSOrderedAscending)
    [[aNotification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
else [[aNotification.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];

这实际上工作正常,但 Xcode 警告我 UIKeyboardBoundsUserInfoKey 已弃用。我怎样才能摆脱这个警告而不必抑制任何其他警告?

另外,有没有办法简单地检查 UIKeyboardBoundsUserInfoKey 是否已定义以避免检查 iOS 版本?我尝试检查它是 NULL 还是 nil,甚至弱链接 UIKit,但似乎没有任何效果。

提前致谢

【问题讨论】:

    标签: objective-c xcode ios


    【解决方案1】:

    由于代码中任何地方存在已弃用的常量都会引发警告(并为我们 -Werror 用户中断构建),因此您可以使用实际的常量值来查找字典。感谢 Apple 通常(总是?)使用常量名称作为它的值。

    至于运行时检查,我认为你更好testing for the new constant

    &UIKeyboardFrameEndUserInfoKey!=nil
    

    所以,这就是我实际获取键盘框架的方法(基于此other answer):

    -(void)didShowKeyboard:(NSNotification *)notification {
        CGRect keyboardFrame = CGRectZero;
    
        if (&UIKeyboardFrameEndUserInfoKey!=nil) {
            // Constant exists, we're >=3.2
            [[notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
            if (UIInterfaceOrientationIsPortrait([[UIDevice currentDevice] orientation])) {
                _keyboardHeight = keyboardFrame.size.height;
            }
            else {
                _keyboardHeight = keyboardFrame.size.width;
            }   
        } else {
            // Constant has no value. We're <3.2
            [[notification.userInfo valueForKey:@"UIKeyboardBoundsUserInfoKey"] getValue: &keyboardFrame];
            _keyboardHeight = keyboardFrame.size.height;
        }
    }
    

    我实际上在 3.0 设备和 4.0 模拟器上对此进行了测试。

    【讨论】:

    • 谢谢!这正是我想要的。
    • 如果其他人遇到此代码,请注意它不是您要查找的内容。返回的keyboardFrame 没有考虑界面方向,并且 if (UIInterfaceOrientationIsPortrait) 行会在各种情况下(特别是当设备平放在桌子上而不是直立时)给你错误的答案。相反,您要做的是使用 [self.view convertRect:keyboardFrame fromView:nil] 将未转换的窗口坐标转换为视图坐标。这将旋转框架,以便始终使用正确的高度。
    【解决方案2】:

    【讨论】:

    • 我知道用什么代替 UIKeyboardBoundsUserInfoKey,我要问的是如何在不收到 Xcode 警告的情况下保持与 3.1.3 的兼容性。
    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多