There are a lot of apps nowadays which we want to use in only landscape or portrait mode according to our preference. Today we are going to implement lock screen orientation in swift.
We can set orientation according to our requirement i.e. portrait or landscape. Let’s check how can we implement lock screen orientation in swift.
Step 1: Create a new iOS project & select device orientation as per the requirement in Runner.
Step 2: Add supported Orientation method in App Delegate.
1 |
var orientationLock = UIInterfaceOrientationMask.all |
1 2 3 4 |
private func applicationWindow(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow) -> UIInterfaceOrientationMask{ return self.orientationLock } |
Step 3: Create 2 buttons for selecting the landscape & portrait orientation.
Step 4: Create action outlets for these buttons in view controller.
Step 5: Create a global helper class to adjust the lock & rotate it to the desired orientation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
struct AppUtility { static func lockOrientation(_ orientation: UIInterfaceOrientationMask) { if let delegate = UIApplication.shared.delegate as? AppDelegate { delegate.orientationLock } } static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) { self.lockOrientation(orientation) UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation") UINavigationController.attemptRotationToDeviceOrientation() } } |
Step 6: Use lockOrientation method on the button action in the view controller to lock orientation & rotate the screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
override func viewWillDisappear(_ animated: Bool) { AppUtility.lockOrientation(.allButUpsideDown) } @IBAction func landscapeButton(_ sender: Any) { AppUtility.lockOrientation(.landscape, andRotateTo: .landscapeLeft) } @IBAction func portraitButton(_ sender: Any) { AppUtility.lockOrientation(.portrait, andRotateTo: .portrait) } |
OUTPUT:
CONCLUSION:
In this article, I have explained how to lock screen orientation, which you can modify and experiment with according to your own.
Thanks for reading this article ❤
If I got something wrong 🙈, let me know in the comments. I would love to improve.
For more interesting blogs check out here – https://mobikul.com/blog/
Reference link: https://www.polpiella.dev/changing-orientation-for-a-single-screen-in-swiftui