this can be done in two ways.
1 .personally I prefer this way
1.1 keep this function in AppDelegate to handle the orientation(this is must)
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return .all
}
1.2 in which ViewController you want the force orientation, go to that view controller and add these lines in the variable declaring section
var forceLandscape: Bool = false
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
forceLandscape ? .landscape : .portrait
}
we will be updating the forceLandscape so it will get updated, then the supportedInterfaceOrientations also will get updated
1.3 Here we are setting the trigger for updating the forceLandscape (we can add these lines of code inside button action for handling IOS 16 force roatation)
if #available(iOS 16.0, *) {
self.forceLandscape = true
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else { return }
self.setNeedsUpdateOfSupportedInterfaceOrientations()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: .landscapeRight)){
error in
print(error)
print(windowScene.effectiveGeometry)
}
})
this will update the forceLandscape, so it will check the orientation and update according to it
Above lines of code is for one way, another way is given below
2. Another way is updating orientation in AppDelegate class:
2.1 keep this function and property in AppDelegate to handle the orientation(this is must)
var orientation : UIInterfaceOrientationMask = .portrait
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return orientation
}
2.2 In the viewcontroller button action we can update the propperty
@IBAction func buttonAction(_ sender: Any) {
let appDel = UIApplication.shared.delegate as! AppDelegate
appDel.orientation = .landscape
if #available(iOS 16.0, *) {
DispatchQueue.main.async {
let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
self.setNeedsUpdateOfSupportedInterfaceOrientations()
self.navigationController?.setNeedsUpdateOfSupportedInterfaceOrientations()
windowScene?.requestGeometryUpdate(.iOS(interfaceOrientations: .landscape)) { error in
print(error)
print(windowScene?.effectiveGeometry ?? "")
}
}
}else{
UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
}