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.

Render Metal with passthrough in visionOS
Get ready to extend your Metal experiences for visionOS. Learn best practices for integrating your rendered content with people’s physical environments with passthrough. Find out how to position rendered content to match the physical world, reduce latency with trackable anchor prediction, and more.

Explore game input in visionOS
Discover how to design and implement great input for your game in visionOS. Learn how system gestures let you provide frictionless ways for players to interact with your games. And explore best practices for supporting custom gestures and game controllers.

Enhance your UI animations and transitions
Explore how to adopt the zoom transition in navigation and presentations to increase the sense of continuity in your app, and learn how to animate UIKit views with SwiftUI animations to make it easier to build animations that feel continuous.