2014-10-29 72 views
0

我試圖改寫在Objective-C斯威夫特在iOS項目在Xcode 6.1的UIImageView旋轉值,但我無法「翻譯」這一目標-C線:獲取斯威夫特

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

哪有我在Swift中獲得了我的UIImageView旋轉值?

回答

7

它是隻稍稍雨燕更復雜,因爲valueForKeyPath回報 的可選必須被解開的則顯式轉換爲NSNumber。 這可以(例如)用的可選鏈接 和任選的鑄造的組合來實現:

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

最後的「零 - 合併運算符」 ??將值設置爲0.0如果鍵路徑不是 集(或不是NSNumber),這模仿了Objective-C的行爲,其中 發送floatValue消息到nil也將返回0.0

+0

非常感謝你,那就是我一直在尋找的! – 2014-11-03 17:21:44