How to Change the Device Orientation Programmatically in iOS 6

How to change Device Orientation programmatically in Swift?

For each VC declare this variable w/ desired orientation. This is for portrait.

override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait }   

Then on appearance enforce the desired orientation.

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.setAnimationsEnabled(false)
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
UIView.setAnimationsEnabled(true)
}

Change orientation programmatically with button - iOS

I don't have a swift code. Below are the objective c code, It worked for me. You can convert it into swift as per your requirement.

Ojective C

UIInterfaceOrientation currentOrientation = [UIApplication sharedApplication].statusBarOrientation;
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];
[UIViewController attemptRotationToDeviceOrientation];

Update

Swift 4.0

var value  = UIInterfaceOrientation.landscapeRight.rawValue
if UIApplication.shared.statusBarOrientation == .landscapeLeft || UIApplication.shared.statusBarOrientation == .landscapeRight{
value = UIInterfaceOrientation.portrait.rawValue
}

UIDevice.current.setValue(value, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()

Above code already tested by me and it is working fine. Incase above code is not worked for you, Then execute it after some delay using performSelector.

How to get current orientation of device programmatically in iOS 6?

You can try this, may help you out:

How to change the device orientation programmatically in iOS 6

OR

Objective-c:

UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]

Swift:

if UIDevice.current.orientation.isLandscape {
// Landscape mode
} else {
// Portrait mode
}

How to set device (UI) orientation programmatically?

That method is called to determine whether your interface should automatically rotate to a given rotation (i.e letting UIKit do the hard work, rather than you doing it manually).

So if you wanted your app to only work in landscape you'd implement the body of that method with:


return UIInterfaceOrientationIsLandscape(interfaceOrientation);

If you wanted your UI to auto rotate to all orientations you could just

return YES;

Is that what you were asking?



Related Topics



Leave a reply



Submit