Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Moncader/be7d7830e4bf64848e89b85f9dbc25a6 to your computer and use it in GitHub Desktop.
Save Moncader/be7d7830e4bf64848e89b85f9dbc25a6 to your computer and use it in GitHub Desktop.
import Foundation
import os.log
public class OrientationFixFlutterViewController : FlutterViewController {
fileprivate var _orientationPreferences: UIInterfaceOrientationMask = .all
override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
get { return _orientationPreferences }
}
@objc
func performOrientationUpdate(_ new_preferences: UIInterfaceOrientationMask) {
guard new_preferences != _orientationPreferences else {
return
}
_orientationPreferences = new_preferences;
if #available(iOS 16.0, *) {
for scene in UIApplication.shared.connectedScenes {
guard let windowScene = scene as? UIWindowScene else {
continue
}
let geometryPreferences = UIWindowScene.GeometryPreferences.iOS(interfaceOrientations: _orientationPreferences)
windowScene.requestGeometryUpdate(geometryPreferences) { error in
os_log("Failed to change device orientation: %@", log: OSLog.default, type: .error, error as NSError)
}
setNeedsUpdateOfSupportedInterfaceOrientations()
}
} else {
let currentInterfaceOrientation = UInt(1 << UIApplication.shared.statusBarOrientation.rawValue)
let orientationRaw = UInt(_orientationPreferences.rawValue)
if ((orientationRaw & currentInterfaceOrientation) == 0) {
UIViewController.attemptRotationToDeviceOrientation()
// Force orientation switch if the current orientation is not allowed
if ((orientationRaw & UIInterfaceOrientationMask.portrait.rawValue) != 0) {
// This is no official API but more like a workaround / hack (using
// key-value coding on a read-only property). This might break in
// the future, but currently it´s the only way to force an orientation change
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
} else if ((orientationRaw & UIInterfaceOrientationMask.portraitUpsideDown.rawValue) != 0) {
UIDevice.current.setValue(UIInterfaceOrientation.portraitUpsideDown.rawValue, forKey: "orientation")
} else if ((orientationRaw & UIInterfaceOrientationMask.landscapeLeft.rawValue) != 0) {
UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
} else if ((orientationRaw & UIInterfaceOrientationMask.landscapeRight.rawValue) != 0) {
UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment