2

我正在尝试将 Objective-C 中的 iOS 项目重写为 Xcode 6.1 中的 Swift,但我无法“翻译”这个 Objective-C 行:

CGFloat imageRotation = [[self.imageView valueForKeyPath:@"layer.presentationLayer.transform.rotation.z"] floatValue];

如何在 Swift 中获取 UIImageView 旋转值?

4

1 回答 1

8

它在 Swift 中只是稍微复杂一些,因为它valueForKeyPath返回一个必须解包的可选项,然后显式转换为NSNumber. 这可以(例如)通过可选链接和可选转换的组合来完成:

let zKeyPath = "layer.presentationLayer.transform.rotation.z"
let imageRotation = (self.imageView.valueForKeyPath(zKeyPath) as? NSNumber)?.floatValue ?? 0.0

最后的“nil-coalescing operator”??将值设置为0.0如果键路径未设置(或不是NSNumber),这模仿了 Objective-C 的行为,其中发送floatValue消息到nil也将返回0.0

于 2014-10-29T14:39:48.213 回答