Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift: Rotate Buttons Based On Device Orientation
override func viewDidLoad()
{
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(rotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
@objc func rotate()
{
var rotation_angle: CGFloat = 0
switch UIDevice.current.orientation
{
case .landscapeLeft:
rotation_angle = (CGFloat(Double.pi) / 2)
case .landscapeRight:
rotation_angle = (CGFloat(-Double.pi) / 2)
case .portraitUpsideDown:
rotation_angle = CGFloat(Double.pi)
case .unknown, .portrait, .faceUp, .faceDown:
rotation_angle = 0
}
UIView.animate(withDuration: 0.2, animations:
{
// WHATEVER YOU WANT TO ROTATE HERE
self.SharingButton.transform = CGAffineTransform(rotationAngle: rotation_angle);
}, completion: nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment