我正在尝试将 Objective-C 中的 iOS 项目重写为 Xcode 6.1 中的 Swift,但我无法“翻译”这个 Objective-C 行:
CGFloat imageRotation = [[self.imageView valueForKeyPath:@"layer.presentationLayer.transform.rotation.z"] floatValue];
如何在 Swift 中获取 UIImageView 旋转值?
我正在尝试将 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
最后的“nil-coalescing operator”??
将值设置为0.0
如果键路径未设置(或不是NSNumber
),这模仿了 Objective-C 的行为,其中发送floatValue
消息到nil
也将返回0.0
。