Get the current angle/rotation/radian for a UIView?

IosCocoa TouchUiviewRotation

Ios Problem Overview


How do you get the current angle/rotation/radian a UIView has?

Ios Solutions


Solution 1 - Ios

You can do it this way...

CGFloat radians = atan2f(yourView.transform.b, yourView.transform.a); 
CGFloat degrees = radians * (180 / M_PI);

Solution 2 - Ios

Swift:

// Note the type reference as Swift is now string Strict

let radians:Double = atan2( Double(yourView.transform.b), Double(yourView.transform.a))
let degrees:CGFloat = radians * (CGFloat(180) / CGFloat(M_PI) )

Solution 3 - Ios

A lot of the other answers reference atan2f, but given that we're operating on CGFloats, we can just use atan2 and skip the unnecessary intermediate cast:

Swift 4:
let radians = atan2(yourView.transform.b, yourView.transform.a)
let degrees = radians * 180 / .pi

Solution 4 - Ios

For Swift 3, you could use the following code:

let radians:Float = atan2f(Float(view.transform.b), Float(view.transform.a))
let degrees:Float = radians * Float(180 / M_PI)

Solution 5 - Ios

//For Swift 3: M_PI is depreciated now Use Double.pi

let radians = atan2f(Float(yourView.transform.b), Float(yourView.transform.a));
let degrees = radians * Float(180 / Double.pi)

//For Swift 4:

let radians = atan2(yourView.transform.b, yourView.transform.a)
let degrees = radians * 180 / .pi

Solution 6 - Ios

In swift 2 and Xcode 7 :

let RdnVal = CGFloat(atan2f(Float(NamVyu.transform.b), Float(NamVyu.transform.a)))
let DgrVal = RdnVal * CGFloat(180 / M_PI)

Solution 7 - Ios

Using extensions:

extension UIView {
    
    var rotation: Float {
        let radians:Float = atan2f(Float(transform.b), Float(transform.a))
        return radians * Float(180 / M_PI)
    }
}

Usage:

let view = UIView()
print(view.rotation)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHjalmarView Question on Stackoverflow
Solution 1 - IosKrishnabhadraView Answer on Stackoverflow
Solution 2 - IosPeter KreinzView Answer on Stackoverflow
Solution 3 - IosdwlzView Answer on Stackoverflow
Solution 4 - IosRakesh YembaramView Answer on Stackoverflow
Solution 5 - IosRohit SisodiaView Answer on Stackoverflow
Solution 6 - IosSujay U NView Answer on Stackoverflow
Solution 7 - IosHosseinView Answer on Stackoverflow