Reputation: 13698
I want to use SceneDelegate, UIWindowScene, UIWindowSceneDelegate and other UIScene related things.
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow.init(frame: windowScene.coordinateSpace.bounds)
window?.windowScene = windowScene
let vc = UIStoryboard(name: "FCBottomTabBar", bundle: nil).instantiateInitialViewController()!
window?.rootViewController = vc
window?.makeKeyAndVisible()
}
How can i dynamically lock the orientation for this window? For example for portrait
only? Dynamically means that in runtime when user interacts with something the orientation locks back to all.
For example for screen A i need to lock to only portrait orientation. For screen B to only landscape.
Upvotes: 2
Views: 1255
Reputation: 11
This other answer seems overly complex and uses a private API. In a view controller, to set the supported orientations, simply override supportedInterfaceOrientations
.
For example, to lock it to Portrait orientation:
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
.portrait
}
Upvotes: 0
Reputation: 477
From 'Device orientation' initially make it portrait.
In AppDelegate make a variable 'orientation' and set its value to UIInterfaceOrientationMask.portrait
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
...
var orientation = UIInterfaceOrientationMask.portrait
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return orientation
}
}
Now in your desired ViewController write this to change orientation
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
(UIApplication.shared.delegate as! AppDelegate).orientation = .landscapeLeft
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
Hope it will help you.
Upvotes: 0