write code for rotation in UIViewController

Asked on 08/02/2024

1 search

To implement rotation in a UIViewController, you can use the following code snippet. This example demonstrates how to rotate a view by 90 degrees:

import UIKit

class RotationViewController: UIViewController {
    
    let rotatingView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Setup the view
        rotatingView.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        rotatingView.backgroundColor = .red
        view.addSubview(rotatingView)
        
        // Add a button to trigger the rotation
        let rotateButton = UIButton(type: .system)
        rotateButton.frame = CGRect(x: 100, y: 300, width: 100, height: 50)
        rotateButton.setTitle("Rotate", for: .normal)
        rotateButton.addTarget(self, action: #selector(rotateView), for: .touchUpInside)
        view.addSubview(rotateButton)
    }
    
    @objc func rotateView() {
        UIView.animate(withDuration: 0.5) {
            self.rotatingView.transform = self.rotatingView.transform.rotated(by: .pi / 2)
        }
    }
}

This code sets up a UIViewController with a red square view and a button. When the button is pressed, the red square rotates by 90 degrees (π/2 radians).

For more advanced animations and transitions, you might want to check out the session Enhance your UI animations and transitions from WWDC 2024, which covers various techniques for animating UIKit and SwiftUI views.