Skip to content

Instantly share code, notes, and snippets.

@halgatewood
Last active July 24, 2022 15:28
Show Gist options
  • Save halgatewood/0f77604d41a457ae0ec208ae6cccb220 to your computer and use it in GitHub Desktop.
Save halgatewood/0f77604d41a457ae0ec208ae6cccb220 to your computer and use it in GitHub Desktop.
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