ios - 在 Swift 中获取 UIImageView 旋转值

标签 ios xcode swift rotation presentation-layer

我正在尝试将 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/

相关文章:

ios - 在 UIViewController 中创建的 subview 的弱引用

ios - UITableViewCell - 根据内容选择背景大小

ios - 在 Objective-C 中保存 CNPostalAddress

ios - 从 Swift 2 迁移的项目的 Swift 包管理器

arrays - 对数组索引使用 switch/case

ios - UIBarbuttonItem 关闭 UIVIewcontroller

ios - Swift 中的@IBOutlet 变量

ios - 点击扫描平面时如何将 3D 对象添加到引用图像?

ios - 来自另一个目标的 Swift 伞头

ios - 如何使用 Swift 和 parse.com 在 tableview 中显示图像