I have a view controller and I would like to have the following experience. Inside the view controller i got a button which force rotate the orientation to landscape right.
In Deployment Info - Device Orientation i have enabled "Landscape Right" and "Portrait".
I want to mention that in my device i have enabled the "Portrait Orientation Lock" that's why i want a button to rotate the orientation programmatically with the following code.
let rotateButton: UIButton = {
let btn = UIButton(type: .system)
btn.setTitle("Rotate", for: .normal)
btn.setTitleColor(.red, for: .normal)
btn.addTarget(self, action: #selector(rotateTapped), for: .touchUpInside)
return btn
}()
@objc func rotateTapped() {
let value = UIInterfaceOrientation.landscapeRight.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
So the code above works properly and the screen is rotating. Although i want when the user rotates back to Portrait, the screen to rotate to portrait again without any button pressed. When the "Portrait Orientation Locked" is on, the screen is not rotating back to portrait.
I've tried the following codes with no luck.
1)
NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
@objc func rotated() {
if UIDevice.current.orientation.isLandscape {
print("Landscape") //when the user taps the button this is being printed.
} else {
print("Portrait") //when the user rotates back to portrait this is NOT being printed.
}
}
and 2)
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation == .landscapeRight {
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
}
Any idea of what can it be to change back to portrait when user rotates the phone again?