Reputation: 2317
I'm using Ionic framework with the plugin cordova-plugin-screen-orientation
and I would like to lock my app orientation to be always portrait.
I tried to do it by putting the next line in the config.xml
<preference name="orientation" value="portrait" />
It works on android
but not on ios
. Any suggestions?
Upvotes: 2
Views: 5567
Reputation: 31
I am using Ionic/Capacitor and Vuejs, I also had the same problem with the plugin for iOS. This is what I did and it solved the problem.
To fix the bug to be able to lock the screen to the specified orientation on iOS:
1. Open AppDelegate.swift for your app. You can find this file inside ios/App/App/AppDelegate.swift
2. Add the following code:
var orientationLock = UIInterfaceOrientationMask.all
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return self.orientationLock
}
@objc func setOrientationLock(_ notification: Notification)
{
if let data = notification.userInfo as? [String: Int]
{
for (_, mask) in data
{
switch mask
{
case 1: self.orientationLock = UIInterfaceOrientationMask.portrait
break;
case 2: self.orientationLock = UIInterfaceOrientationMask.portraitUpsideDown
break;
case 3: self.orientationLock = UIInterfaceOrientationMask.landscapeRight
break;
case 4: self.orientationLock = UIInterfaceOrientationMask.landscapeLeft
break;
case 5: self.orientationLock = UIInterfaceOrientationMask.landscape
break;
default: self.orientationLock = UIInterfaceOrientationMask.all
}
}
}
}
3. In the same file locate: "func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {"
4. Add the following code inside the function before the "return true" statement:
NotificationCenter.default.addObserver(self, selector: #selector(self.setOrientationLock), name: NSNotification.Name(rawValue: "CAPOrientationLocked"), object: nil)
5. ionic build, ionic cap copy, ionic cap sync, and problem FIXED!
Upvotes: 0
Reputation: 57309
I hope I'm not late.
You can do it easily but with a different Cordova plugin.
First you will need to use Cordova net.yoik.cordova.plugins.screenorientation plugin.
You can easily programmatically lock/unlock screen orientation using it.
// set to either landscape
screen.lockOrientation('landscape');
// allow user rotate
screen.unlockOrientation();
If you want to do this for all pages/views do it like this:
$ionicPlatform.ready(function() {
screen.lockOrientation('landscape');
});
Next, to do it only on selected pages, use this code inside an appropriate page controller:
$scope.$on('$ionicView.beforeEnter', function(){
screen.lockOrientation('landscape');
});
If executed in a right controller this code will trigger orientation lock before the view becomes visible.
Read this if you want to find out more: http://www.gajotres.net/changing-locking-screen-orientation-in-ionic-application/
Upvotes: 3