I have designed some of my views to be in landscape mode and others in portrait mode. My goal is to prevent them from rotating. Specifically, I want a landscape view to remain in landscape orientation and a portrait view to stay in portrait orientation, without any automatic rotation.
I have researched this extensively and tried the following:
override func shouldAutorotate() -> Bool {
return false
}
And:
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
However, these methods did not work as expected. Does anyone have suggestions on how to enforce a fixed orientation for each view?
just get the orientation with overriding :
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape && flag{
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
print("Landscape")
} else if UIDevice.current.orientation.isPortrait && !flag {
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
print("Portrait")
}
}
and do somthing like this .
this function won't lock your screen but it'll keep the screen at orientation you want.