Skip to content

Instantly share code, notes, and snippets.

@PabloDomine
Last active July 31, 2017 19:03
Show Gist options
  • Save PabloDomine/cb98b13c294504bf267a1139a0fe5cad to your computer and use it in GitHub Desktop.
Save PabloDomine/cb98b13c294504bf267a1139a0fe5cad to your computer and use it in GitHub Desktop.
Subscribe to NotificationCenter's UIDeviceOrientationDidChange to know when to rotate the UI elements
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(MainCameraVC.orientationChanged(notification:)),
name: Notification.Name.UIDeviceOrientationDidChange,
object: nil)
}
func orientationChanged(notification: Notification) {
let deviceOrientation = UIDevice.current.orientation
var angle: Double?
switch deviceOrientation {
case .portrait:
angle = 0
break
case .portraitUpsideDown:
angle = Double.pi
break
case .landscapeLeft:
angle = Double.pi / 2
break
case .landscapeRight:
angle = -Double.pi / 2
break
default:
break
}
if let angle = angle {
let transform = CGAffineTransform(rotationAngle: CGFloat(angle))
UIView.animate(withDuration: 0.3, animations: {
self.label.transform = transform
self.button.transform = transform
...
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment