change return from shouldAutorotateToInterfaceOrientation: at runTime - ios

I'm using shouldAutorotateToInterfaceOrientation: for respond YES to all orientations.
At runtime, in few case, i must change the return to YES only in portrait.
But if i change this return type, and my device not physicly turn, my interface orientation not change.
How can it's possible to force uiView to check the shouldAutorotateToInterfaceOrientation: and rotate the view without UIdevice rotation notification.
Thanks a lot.

Static method starting from IOS 5:
[UIViewController attemptRotationToDeviceOrientation];

Add this two lines of code:
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

Related

Force orientation in ios9

I want to force portrait mode in 2 viewController and 1 viewController with landscape mode,
I have tried older technique , but those are not working in ios9
It's more than likely that you've got some allowed orientations defined in your info.plist. You should check there and remove any entries, as I believe these will override any other values in the project.
You should then be able to set the orientation on each VC with something like:
-(NSUInteger)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskLandscapeRight;
}
-(BOOL)shouldAutorotate {
return NO;
}
I think the key you need to is Supported interface orientations.
You can set the orientation of the viewcontroller from Xib/Storyboard as each viewcontroller have the property "orientation"
and implement method given below
-(BOOL)shouldAutorotate
{
return NO;
}
You can set orientation as bellow in your viewDidAppear method
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:value forKey:#"orientation"];

How change orientations programmatically [duplicate]

This question already has answers here:
Force landscape mode in one ViewController using Swift
(20 answers)
Closed 1 year ago.
In iOS 5 we could change the device orientation programmatically like so:
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];
But in iOS 6 setOrientation is deprecated, how may i change the device orientation programmatically in iOS 6?
Here are my "five cents", tested on iOS7 with ARC
[[UIDevice currentDevice] setValue:
[NSNumber numberWithInteger: UIInterfaceOrientationPortrait]
forKey:#"orientation"];
This doesnt generate "leak" warning as performSelector will.
UIAlertView - with this code, when you open UIAlertView during view(will/Did)appear you will notice that all but this view is in portrait (apple, really?) I wasn't able to force the view to reorient but found that if you put slight delay before opening the UIAlertView then view has time to change orientation.
Note I'm releasing my app week commencing 12/09/2014 and I will update post if it will pass or fail.
I found out that the easiest way to force the device to change orientation is to present a new view controller (using presentViewController:animated:completion:) where the new view controller specified a particular preferred orientation (by implementing the method -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation).
When a new view controller is presented, as expected, the orientation will change to the one preferred by the new view controller. So, simplest implementation (best practice?) will be to embed all functionality you needed in a specific orientation into a separate view controller, and present it as needed. The system will take care of changing the orientation for you.
Obviously this might not suit all use cases, but, fortunately the same trick is applicable to force the device to change orientation for existing view controller.
The trick is to present a new view controller with the specific preferred orientation that you needed, and then hide it immediately. This will cause the orientation to change temporary when the new view controller is presented. The best part is, when the new view controller is dismissed, the original (presenting) view controller's preferredInterfaceOrientationForPresentation is queried again, you can specify the final orientation you want here.
One important thing to look out here is to also temporary disable auto rotation in the original view controller (when coming back from the newly presented-then-dismissed view controller), so that when user rotate their phone towards the new orientation, it does not triggered further auto rotation.
The following code should illustrate my point, my example forces rotation to portrait, just change accordingly if you want other orientation.
Assuming you have the original view controller named Original, and a temporary view controller named ForcePortrait
#interface Original : UIViewController
{
BOOL orientationToPortrait; //should set to NO by default
}
#end
#implementation Original
- (UIInterfaceOrientation) preferredInterfaceOrientationForPresentation
{
if(orientationToPortrait)
{
//when we manually changed, show in Portrait
return UIInterfaceOrientationPortrait;
}
else
{
//before manual orientation change, we allow any orientation
return self.interfaceOrientation;
}
}
-(BOOL) shouldAutorotate
{
//we should 'lock' the rotation once we manually change it
return !orientationToPortrait;
}
-(void) changeOrientationToPortrait
{
//Sample method to change the orientation
//when called, will show (and hide) the temporary view
//Original.preferredInterfaceOrientationForPresentation will be called again after this method
//flag this to ensure that we tell system we prefer Portrait, whenever it asked again
orientationToPortrait = YES;
//presenting the following VC will cause the orientation to temporary change
//when the new VC is dismissed, system will ask what is our (Original) orientation preference again
ForcePortrait* forcePortrait = [[ForcePortrait alloc] init];
[self presentViewController:forcePortrait animated:NO completion:^{
[forcePortrait dismissViewControllerAnimated:NO completion:nil];
}];
}
#end
#interface ForcePortrait : UIViewController
#end
#implementation ForcePortrait
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
#end
This does not answer how to change the device Orientation, but an additional information that might help you.
iOS 6 UI Interface Orientation - shouldAutorotateToInterfaceOrientation: Not Working
The method shouldAutorotateToInterfaceOrientation: is NOT supported in iOS 6. Its deprecated. Just in case if you are a newbie, who just stared working in cocoa, and wondering why is your view controller messed up in iOS 6 and perfect in iOS 5, just know that shouldAutorotateToInterfaceOrientation: is not supported anymore. Even though it may work well with Xcode 4 to 4.3 it will NOT work on Xcode 4.5.
Apple provides a new method to get this thing done, in a much cleaner fashion. You use supportedInterfaceOrientations instead. It returns all of the interface orientations that the view controller supports, a mask of interface orientation values.
UIInterfaceOrientationMask Enum:
These constants are mask bits for specifying a view controller’s supported interface orientations.
typedef enum {
UIInterfaceOrientationMaskPortrait = (1 << UIInterfaceOrientationPortrait),
UIInterfaceOrientationMaskLandscapeLeft = (1 << UIInterfaceOrientationLandscapeLeft),
UIInterfaceOrientationMaskLandscapeRight = (1 << UIInterfaceOrientationLandscapeRight),
UIInterfaceOrientationMaskPortraitUpsideDown = (1 << UIInterfaceOrientationPortraitUpsideDown),
UIInterfaceOrientationMaskLandscape =
(UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight),
UIInterfaceOrientationMaskAll =
(UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft |
UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortraitUpsideDown),
UIInterfaceOrientationMaskAllButUpsideDown =
(UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft |
UIInterfaceOrientationMaskLandscapeRight),
} UIInterfaceOrientationMask;
Using shouldAutorotateToInterfaceOrientation: method:
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
return UIInterfaceOrientationIsLandscapeRight(toInterfaceOrientation);
}
Using supportedInterfaceOrientations method:
-(NSUInteger)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskLandscapeRight;
}
These are the added methods to UIViewController regarding Orientation in iOS6
UIViewController preferredInterfaceOrientationForPresentation
UIViewController shouldAutorotate
UIViewController supportedInterfaceOrientations
Added methods to UIApplication regarding Orientation in iOS6
UIApplication supportedInterfaceOrientationsForWindow:
UIInterfaceOrientationMask
Try this:
#import <objc/message.h>
if(UIDeviceOrientationIsLandscape(self.interfaceOrientation)){
if ([[UIDevice currentDevice] respondsToSelector:#selector(setOrientation:)])
{
objc_msgSend([UIDevice currentDevice], #selector(setOrientation:), UIInterfaceOrientationPortrait );
}
}
You should place
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
in your AppDelegate didFinishLaunchingWithOptions Method.
Then, anywhere in your application you can get the current orientation with:
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
And test orientation with:
UIInterfaceOrientationIsPortrait(orientation)
UIInterfaceOrientationIsLandscape(orientation)
as, like
if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation))
{
// code for landscape orientation
// OR
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];
// OR
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeLeft];
}
else if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
{
// code for Portrait orientation
// OR
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortraitUpsideDown];
// OR
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait];
}
This code is for iOS 8 or later
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:value forKey:#"orientation"];
Try this...It worked out for me...
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
UIView *view = [window.subviews objectAtIndex:0];
[view removeFromSuperview]; [window addSubview:view];
#implementation UINavigationController (autorotate)
-(NSUInteger)supportedInterfaceOrientations
{
//make the check for iphone/ipad here
if(IPHONE)
{
return UIInterfaceOrientationMaskPortrait;
}
else
{
return UIInterfaceOrientationMaskLandscape;
}
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
- (BOOL)shouldAutorotate
{
return NO;
}
A little modification to Bissy's answer, if you want to avoid using Runtime Library:
if (UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation]))
{
if ([[UIDevice currentDevice] respondsToSelector:#selector(setOrientation:)])
{
int orientationPortrait = UIInterfaceOrientationPortrait;
NSMethodSignature *sig = [[UIDevice currentDevice] methodSignatureForSelector:#selector(setOrientation:)];
NSInvocation* invo = [NSInvocation invocationWithMethodSignature:sig];
[invo setTarget:[UIDevice currentDevice]];
[invo setSelector:#selector(setOrientation:)];
[invo setArgument:&orientationPortrait atIndex:2];
[invo invoke];
}
}
This works for iOS7, force autorotate to portrait.
//In your viewController.m
#import <objc/message.h>
// for autorotate viewController to portraid
- (void)viewWillAppear:(BOOL)animated {
UIInterfaceOrientation orientationStatusBar =[[UIApplication sharedApplication] statusBarOrientation];
switch (orientationStatusBar) {
case UIInterfaceOrientationPortrait:break;
case UIInterfaceOrientationLandscapeLeft:
objc_msgSend([UIDevice currentDevice], #selector(setOrientation:), UIInterfaceOrientationPortrait);
break;
case UIInterfaceOrientationLandscapeRight:
objc_msgSend([UIDevice currentDevice], #selector(setOrientation:), UIInterfaceOrientationPortrait);
break;
default:
break;
}
}
// this permit autorotate
- (BOOL) shouldAutorotate
{
// this lines permit rotate if viewController is not portrait
UIInterfaceOrientation orientationStatusBar =[[UIApplication sharedApplication] statusBarOrientation];
if (orientationStatusBar != UIInterfaceOrientationPortrait) {
return YES;
}
//this line not permit rotate is the viewController is portrait
return NO;
}
NOTE: I implemented this option in my app, but probably would get rejected by Apple (comment for Austin for edited 6 of Sergey K. in oct 2012).
Apple made changing the device orientation programmatically in ios6 quite difficult (on purpose mind you).
As far as I know the only way to accomplish what you're asking is to simulate the change of device orientation.
Using setTransform to rotate the UIView and re-applying its own frame gives the desired results.
[YourView setTransform:CGAffineTransformMakeRotation(1.57)];
[YourView setFrame:CGRectMake(0, 0, YourView.frame.size.width, YourView.frame.size.height)];
And when the device physical orientation changes we can undo the transformation.
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[YourView setTransform:CGAffineTransformMakeRotation(0)];
[YourView setFrame:CGRectMake(0, 0, YourView.frame.size.width, YourView.frame.size.height)];
}
if (self.interfaceOrientation != UIInterfaceOrientationLandscapeRight) {
// http://stackoverflow.com/questions/181780/is-there-a-documented-way-to-set-the-iphone-orientation
// http://openradar.appspot.com/radar?id=697
// [[UIDevice currentDevice] setOrientation: UIInterfaceOrientationLandscapeRight]; // Using the following code to get around apple's static analysis...
[[UIDevice currentDevice] performSelector:NSSelectorFromString(#"setOrientation:") withObject:(id)UIInterfaceOrientationLandscapeRight];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return NO;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return interfaceOrientation == UIInterfaceOrientationPortrait
|| interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown ;
}
This works for me on Xcode 6 & 5.
- (BOOL)shouldAutorotate {return YES;}
- (NSUInteger)supportedInterfaceOrientations {return (UIInterfaceOrientationMaskPortrait);}
Its interesting how others didn't run to problems after not setting it like this :
+ (void)setOrientation:(UIDeviceOrientation)orientation {
[UIDevice.currentDevice setValue:#(orientation) forKey:#"orientation"];
[UIViewController attemptRotationToDeviceOrientation];
[UIDevice.currentDevice setValue:#(UIDeviceOrientationUnknown) forKey:#"orientation"];
}
My requirement was to be able to force orientation and then again rotate to device natural orientation... there is UIDeviceOrientationDidChangeNotification that can get you de information to witch orientation to rotate device back but actually it will partly not work if you don't set to unknown immediately after you changed orientation in UIDevice, also there are more details to make it cool but will leave it, as it is out of context of this simple question.

In IOS 6 on iPad, initial rotation is always portrait, after that it always rotates correctly

In a shipping app that has worked correctly under iOS 5.X and supports all orientations, built against iOS 6 it always starts in portrait even when the ipad/simulator is in landscape).
I did add the new rotation methods
- (BOOL)shouldAutorotate NS_AVAILABLE_IOS(6_0);
- (NSUInteger)supportedInterfaceOrientations NS_AVAILABLE_IOS(6_0);
but that makes no difference.
Note we do not use a navigation controller as the root view controller. Otherwise the app rotates correctly after the initial problem.
The root view controller handles all the decision making for rotations and is added to the main window as
self.window.rootViewController = viewController;
I have all the rotations in the plist key set UISupportedInterfaceOrientations~ipad
Any ideas why the initial rotation is ignored?
Under 5.1 it calls shouldAutorotateToInterfaceOrientation and willRotateToInterfaceOrientation, etc. correctly but not under 6.0. If I build against 5.1 SDK then all is well.
After talking with Apple, they claim it is a bug in Xcode 4.5 on existing projects. Either you can create a new project and re-add everything (hard to do with a big project like ours). Or add you rotation logic something like this:
- (void)viewWillLayoutSubviews
{
if ( ! afterFirstTime )
{
[self handleRotationFor:self.interfaceOrientation];
afterFirstTime = YES;
}
}
- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[self handleRotationFor:toInterfaceOrientation];
}
on your root view controller. I got this answer right before their break Thanksgiving week so it might be a little sketchy, but this code does work.
If your application support portrait view, as MusiGenesis said; "iPad apps always start in portrait (even if the device is landscape) in iOS 5 as well."
But i found a solution to start in device orientation.
You can set the initial rotation in the root ViewController, after viewDidLoad function as below.
The code seems to be pointless but it works.
No need to handle portrait rotation.
-(void)viewDidLoad {
[super viewDidLoad];
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) {
[[UIDevice currentDevice] performSelector:NSSelectorFromString(#"setOrientation:") withObject:(id)UIInterfaceOrientationLandscapeLeft];
}
else if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) {
[[UIDevice currentDevice] performSelector:NSSelectorFromString(#"setOrientation:") withObject:(id)UIInterfaceOrientationLandscapeRight];
}
}
Regards.

iOS: How do I figure out the current orientation in viewWillAppear?

I have a UIWebView that I would like to load different URLs depending on whether its portrait or landscape. How can I figure out what my current orientation is inside viewWillAppear?
Use UIApplication's statusBarOrientation property. You may run into problems if you use the device orientation if it is UIDeviceOrientationFaceUp or UIDeviceOrientationFaceDown.
Example
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsLandscape(orientation))
{
// Do something when in landscape
}
else
{
// Do something when in portrait
}
UIDeviceOrientation getCurrentOrientation() {
UIDevice *device = [UIDevice currentDevice];
[device beginGeneratingDeviceOrientationNotifications];
UIDeviceOrientation currentOrientation = device.orientation;
[device endGeneratingDeviceOrientationNotifications];
return currentOrientation;
}
It's up to you to convert the UIDeviceOrientation to UIInterfaceOrientation.
When the app loads, it does not know its current orientation-
UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIDeviceOrientationPortrait) {
NSLog(#"portrait");// only works after a rotation, not on loading app
}
Once you rotate the device, you get correct orientation, but when the app is loaded, without changing the orientation, it seems that using [[UIDevice currentDevice] orientation] doesn't know the current orientation.
So you need to do 2 things -
Try setting the application's accepted device orientations in the plist file
In your UIViewControllers, you will need to override the shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation) method to return YES when the app should rotate:
If the is sequencing of relevant calls mean that you can't rely on interfaceOrientation having the correct value at viewWillAppear then — assuming the parent view controller rotates — the safest thing is probably self.parentViewController.interfaceOrientation. Failing that you could try making a first assumption from [[UIDevice currentDevice] orientation], which may not always be 100% on the money (e.g. if the device is lying flat on a table when your app is launched) but is likely to give you a better guess than always assuming portrait.

how to deal with UIDeviceOrientationFaceUp and UIDeviceOrientationFaceDown?

a noob question here.
i detect the orientation with:
UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
all is fine and dandy and I reposition my text fields and labels according to the reported orientation with
if (orientation == UIDeviceOrientationPortrait || orientation == UIDeviceOrientationPortraitUpsideDown)
and else{} for everything else
the problem that i only recently discovered is when the UIDevice reports UIDeviceOrientationFaceUp or UIDeviceOrientationFaceDown. how do I deal with this situation ? how do I know whether UIDeviceOrientationFaceUp and UIDeviceOrientationFaceDown is happening in Portrait or Landscape ? I know that the device is facing up or down, but I don't know if I should reposition everything to Portrait or Landscape.
thank you!
Apple recommends against using device orientation for view layout. Instead, each view controller has an interfaceOrientation property, and UIApplication has a statusBarOrientation property, both of which will return the current interface orientation, which is suitable for view layout.
To monitor for changes, there are UIViewController methods like willRotateToInterfaceOrientation:duration: that will be called and notifications such as UIApplicationWillChangeStatusBarOrientationNotification that will be posted when an interface orientation change occurs.
A bit late, hopefully it would help some one.
For iOS 6.0 and later:
1) Set this code during your View Setup to receive rotation notification:
// Set Listener to receive orientation notifications from the device
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(detectOrientation)
name:UIDeviceOrientationDidChangeNotification
object:nil];
2) Set this code to catch the Notification after rotation:
-(void)detectOrientation{
switch ([[UIDevice currentDevice] orientation]) {
case UIDeviceOrientationFaceDown:{
NSLog(#"UIDeviceOrientationFaceDown");
break;
}
case UIDeviceOrientationFaceUp:{
NSLog(#"UIDeviceOrientationFaceUp");
break;
}
case UIDeviceOrientationLandscapeLeft:{
NSLog(#"UIDeviceOrientationLandscapeLeft");
break;
}
case UIDeviceOrientationLandscapeRight:{
NSLog(#"UIDeviceOrientationLandscapeRight");
break;
}
case UIDeviceOrientationPortrait:{
NSLog(#"UIDeviceOrientationPortrait");
break;
}
case UIDeviceOrientationPortraitUpsideDown:{
NSLog(#"UIDeviceOrientationPortraitUpsideDown");
break;
}
case UIDeviceOrientationUnknown:{
NSLog(#"UIDeviceOrientationUnknown");
break;
}
default:{
break;
}
}
}
I have the same problems with
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
This method generate notifications for 7 possible device positional states:
UIDeviceOrientationPortrait
UIDeviceOrientationPortraitUpsideDown
UIDeviceOrientationLandscapeLeft
UIDeviceOrientationLandscapeRight
UIDeviceOrientationFaceUp
UIDeviceOrientationFaceDown
UIDeviceOrientationUnknown
But I only need the first 4, well this is my approach to solve this problem (with code included):
How to handle UIDeviceOrientation for manage views layouts

Resources