我正在尝试将 Objective-C 中的 iOS 项目重写为 Xcode 6.1 中的 Swift,但我无法“翻译”这一 Objective-C 行:
CGFloat imageRotation = [[self.imageView valueForKeyPath:@"layer.presentationLayer.transform.rotation.z"] floatValue];
如何在 Swift 中获取我的 UIImageView 旋转值?
最佳答案
它在 Swift 中只是稍微复杂一点,因为 valueForKeyPath
返回
一个可选的,它必须被解包然后显式地转换为NSNumber
。
这可以(例如)通过可选链接的组合来完成
和可选类型转换:
let zKeyPath = "layer.presentationLayer.transform.rotation.z"
let imageRotation = (self.imageView.valueForKeyPath(zKeyPath) as? NSNumber)?.floatValue ?? 0.0
如果键路径不是
设置(或者不是 NSNumber
),这模仿了 Objective-C 的行为,其中
将 floatValue
消息发送到 nil
也会返回 0.0
。
关于ios - 在 Swift 中获取 UIImageView 旋转值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26632507/