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?
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)
}
How to change the device orientation programmatically and screen's rotation direction should be in clock wise direction
Each orientation in iOS has a raw value.
- portrait = 1
- portraitUpsideDown = 2
- landscapeLeft = 3
- landscapeRight = 4
You can change orientation based on these values.
Here is how I have done it in swift
Rotate in clockwise direction:
@IBAction func rotateClockwise(_ sender: Any) {
let orientation = UIDevice.current.orientation
print("Current state:",orientation.rawValue)
var newOrientation: Int {
switch orientation.rawValue {
case 1:
return 3
case 2:
return 4
case 3:
return 2
case 4:
return 1
default:
return 1
}
}
UIDevice.current.setValue(newOrientation, forKey: "orientation")}
Rotate in anti clockwise direction:
@IBAction func rotateAntiClockwise(_ sender: Any) {
let orientation = UIDevice.current.orientation
print("Current state:",orientation.rawValue)
var newOrientation: Int {
switch orientation.rawValue {
case 1:
return 4
case 2:
return 3
case 3:
return 1
case 4:
return 2
default:
return 1
}
}
UIDevice.current.setValue(newOrientation, forKey: "orientation")
}
Note
Make sure to select all orientations in target - general
If that doesn't work add the following code to view controller class
override var supportedInterfaceOrientations: UIInterfaceOrientationMask { get { return .all } }
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 update the UI when the device orientation changed in Swift?
Actually by using
loginView.frame = CGRect(origin: .zero, size: view.bounds.size)
you assign a frame to your login view which will not change on device rotation.
you might wanna use a constraint approach here as well:
// try replacing
// loginView.frame = CGRect(origin: .zero, size: view.bounds.size)
// with
loginView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
loginView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
loginView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
loginView.topAnchor.constraint(equalTo: view.topAnchor),
loginView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
Another approach would be updating the frame of your login view e.g.
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
loginView.frame = CGRect(origin: .zero, size: view.bounds.size)
}
Last but not least you can use autoresizingMask in viewDidLoad
loginView.frame = CGRect(origin: .zero, size: view.bounds.size)
loginView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
P.S. My previous comment was misleading since the login frame wasn't set in the setupStackView() function
and my final comment:
// you can replace
loginView.frame = CGRect(origin: .zero, size: view.bounds.size)
// with
loginView.frame = view.bounds
Setting device orientation in Swift iOS
You can paste these methods in the ViewController of each view that needs to be portrait:
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
How to add device orientation to project programmatically in Swift?
No, not exactly. You need to set up all the possible user interface orientations your app's view controllers MIGHT support in info.plist. Once you've done that there are view controller methods the system calls to see what orientations an individual view controller supports. (See supportedInterfaceOrientations
in the docs.)
As of iOS 8 we're not supposed to use rotation methods any more, so check the docs carefully. It looks to me like supportedInterfaceOrientations
is still supported, but the willRotate...
, willAnimateRotation...
, didRotateFromInterfaceOrientation
, etc, are deprecated.
I suggest reading about user interface rotation in the UIViewController class reference (in Xcode or in Apple's online documentation on the web.)
Related Topics
Create a Copy of a Uiview in Swift
How to Get a Nsurl from an Xcassets Bundle
Removing Duplicates from Array of Custom Objects Swift
Xcode: "This App Could Not Be Installed at This Time."
Use a Generic Class as a Custom View in Interface Builder
Type 'Any' Has No Subscript Members (Firebase)
How to Disable/Remove Firebaseanalytics
Handling Push Notifications When App Is Terminated
Convert an iOS Objective C Object to a JSON String
How to Get Image Metadata in iOS
Storyboard View Elements Greyed Out
Send Messages Between iOS and Watchos with Watchconnectivity in Watchos2
Test Whether a Uiview Is in the Middle of Animation
Gamecenter Authentication in Landscape-Only App Throws Uiapplicationinvalidinterfaceorientation
Looping Through Nsattributedstring Attributes to Increase Font Size