【问题标题】:Get object from [NSString: AnyObject] as UIViewAnimationCurve?从 [NSString: AnyObject] 获取对象作为 UIViewAnimationCurve?
【发布时间】:2015-05-02 15:40:45
【问题描述】:

我有以下代码:

    let userInfo = notification.userInfo

    let animationCurve = userInfo?[UIKeyboardAnimationCurveUserInfoKey] as UIViewAnimationCurve
    let animationDuration = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as NSTimeInterval
    let keyboardFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as CGRect

userInfo 是一个[NSObject: AnyObject]? 字典,UIKeyboardAnimationCurveUserInfoKey 键都是NSString!s。现在我想从这本字典中获取一些元素。但似乎并非我想使用的所有项目都继承自 AnyObjectUIViewAnimationCurveenumCGRectstruct

我正在从 Objective-C 翻译这段代码,其中使用了以下语法:

[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];

现在我想知道如何在不使用(不安全的)指针的情况下从字典中获取这些元素。

【问题讨论】:

  • 有关 UIKeyboardFrameEndUserInfoKey,请参见 stackoverflow.com/a/25381771/1187415。类似的代码应该适用于 UIKeyboardAnimationCurveUserInfoKey。
  • 这适用于 CGRect,但不适用于 UIViewAnimationCurve,因为这是一个枚举。我想我会将它转换为Int,然后使用它的原始值来初始化它,我猜。

标签: ios objective-c swift dictionary


【解决方案1】:

UIKeyboardFrameEndUserInfoKey 的值是一个NSValue 代表 CGRect:

if let tmp = userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
    let keyboardFrame = tmp.CGRectValue()
}

UIKeyboardAnimationCurveUserInfoKey 的值为NSNumber 表示枚举的整数值:

if let tmp = userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
    let animationCurve = UIViewAnimationCurve(rawValue: tmp.integerValue)!
}

这可以组合成单个表达式,使用 nil-coalescing 运营商?? 提供默认值:

let keyboardFrame = (userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() ?? CGRectZero
let animationCurve = UIViewAnimationCurve(rawValue:
        (userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.integerValue ?? 0
    ) ?? .Linear

【讨论】:

  • 好的,谢谢。这行得通。我在哪里可以找到关于这本字典中哪些键的文档?
  • @vrwim:UIWindow 文档中描述了所有键。
猜你喜欢
  • 2014-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
相关资源
最近更新 更多