In my app, the orientation is portrait by default, but in some special screens I want the viewcontroller to be auto rotated or to force the orientation to landscape.
in AppDelegate.swift :
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// portrait by default
var interfaceOrientations:UIInterfaceOrientationMask = .portrait {
didSet{
// force to portrait
if interfaceOrientations == .portrait {
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue,
forKey: "orientation")
}
// force to landscape
else if !interfaceOrientations.contains(.portrait){
UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue,
forKey: "orientation")
}
}
}
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return interfaceOrientations
}
in only portrait vc:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
appDelegate.interfaceOrientations = .portrait
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
appDelegate.interfaceOrientations = .portrait
}
in auto rotated vc:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
appDelegate.interfaceOrientations = .allButUpsideDown
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
appDelegate.interfaceOrientations = .portrait
}
in only landscape vc:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
appDelegate.interfaceOrientations = [.landscapeLeft, .landscapeRight]
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
appDelegate.interfaceOrientations = .portrait
}
but it still has bugs...Help me