Get UIImageView rotation value in Swift

1.5k Views Asked by At

I'm trying to rewrite an iOS project in Objective-C to Swift in Xcode 6.1 but I can't "translate" this Objective-C line :

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

How can I get my UIImageView rotation value in Swift?

1

There are 1 best solutions below

0
Martin R On BEST ANSWER

It is only slightly more complex in Swift because valueForKeyPath returns an optional which has to be unwrapped an then explicitly cast to NSNumber. This can (for example) be done with a combination of optional chaining and optional cast:

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

The final "nil-coalescing operator" ?? sets the value to 0.0 if the key path is not set (or is not an NSNumber), this mimics the behaviour of Objective-C where sending the floatValue message to nil would also return 0.0.