在iOS中已弃用的常量

4

我正在开发一个针对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版本?我尝试检查它是否为NULLnil,甚至使用弱链接UIKit,但似乎没有任何效果。

提前感谢。

2个回答

4

由于代码中存在废弃常量会引发警告(并且对于我们使用-Werror的用户会导致构建失败),因此您可以使用实际的常量值来查找字典。感谢苹果通常(总是?)将常量名称用作其值。

至于运行时检查,我认为您最好测试新常量

&UIKeyboardFrameEndUserInfoKey!=nil

所以,这是我实际上根据此其他答案获取键盘框架的方法:

-(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模拟器上进行了测试。


1
如果其他人遇到此代码,请注意它不完全是您要寻找的内容。返回的keyboardFrame没有考虑界面方向,而if(UIInterfaceOrientationIsPortrait)行将在各种情况下为您提供错误答案(特别是当设备平放在桌子上而不是直立时)。相反,您想要做的是使用[self.view convertRect:keyboardFrame fromView:nil]将未变换的窗口坐标转换为视图坐标。这将旋转框架,使高度始终是正确的要使用的高度。 - MrCranky

0

1
我知道在UIKeyboardBoundsUserInfoKey之外该使用什么,我的问题是如何在不收到Xcode警告的情况下保持与3.1.3的兼容性。 - Pablo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接