I have an app where I would like to support device rotation in certain views but other don't particularly make sense in Landscape mode, so as I swapping the views out I would like to force the rotation to be set to portrait.
There is an undocumented property setter on UIDevice that does the trick but obviously generates a compiler warning and could disappear with a future revision of the SDK.
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait];
Are there any documented ways to force the orientation?
Update: I thought I would provide an example as I am not looking for shouldAutorotateToInterfaceOrientation as I have already implemented that.
I want my app to support landscape and portrait in View 1 but only portrait in View 2. I have already implemented shouldAutorotateToInterfaceOrientation for all views but if the user is in landscape mode in View 1 and then switches to View 2, I want to force the phone to rotate back to Portrait.
This is long after the fact, but just in case anybody comes along who isn't using a navigation controller and/or doesn't wish to use undocumented methods:
UIViewController *c = [[UIViewController alloc]init];
[self presentModalViewController:c animated:NO];
[self dismissModalViewControllerAnimated:NO];
[c release];
It is sufficient to present and dismiss a vanilla view controller.
Obviously you'll still need to confirm or deny the orientation in your override of shouldAutorotateToInterfaceOrientation. But this will cause shouldAutorotate... to be called again by the system.
If you want to force it to rotate from portrait to landscape here is the code. Just note that you need adjust the center of your view. I noticed that mine didn't place the view in the right place. Otherwise, it worked perfectly. Thanks for the tip.
if(UIInterfaceOrientationIsLandscape(self.interfaceOrientation)){
[UIView beginAnimations:#"View Flip" context:nil];
[UIView setAnimationDuration:0.5f];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
self.view.transform = CGAffineTransformIdentity;
self.view.transform = CGAffineTransformMakeRotation(degreesToRadian(90));
self.view.bounds = CGRectMake(0.0f, 0.0f, 480.0f, 320.0f);
self.view.center = CGPointMake(160.0f, 240.0f);
[UIView commitAnimations];
}
From what I can tell, the setOrientation: method doesn't work (or perhaps works no longer). Here's what I'm doing to do this:
first, put this define at the top of your file, right under your #imports:
#define degreesToRadian(x) (M_PI * (x) / 180.0)
then, in the viewWillAppear: method
[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];
if (self.interfaceOrientation == UIInterfaceOrientationPortrait) {
self.view.transform = CGAffineTransformIdentity;
self.view.transform = CGAffineTransformMakeRotation(degreesToRadian(90));
self.view.bounds = CGRectMake(0.0, 0.0, 480, 320);
}
if you want that to be animated, then you can wrap the whole thing in an animation block, like so:
[UIView beginAnimations:#"View Flip" context:nil];
[UIView setAnimationDuration:1.25];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];
if (self.interfaceOrientation == UIInterfaceOrientationPortrait) {
self.view.transform = CGAffineTransformIdentity;
self.view.transform = CGAffineTransformMakeRotation(degreesToRadian(90));
self.view.bounds = CGRectMake(0.0, 0.0, 480, 320);
}
[UIView commitAnimations];
Then, in your portrait mode controller, you can do the reverse - check to see if its currently in landscape, and if so, rotate it back to Portrait.
I was having an issue where I had a UIViewController on the screen, in a UINavigationController, in landscape orientation. When the next view controller is pushed in the flow, however, I needed the device to return to portrait orientation.
What I noticed, was that the shouldAutorotateToInterfaceOrientation: method isn't called when a new view controller is pushed onto the stack, but it is called when a view controller is popped from the stack.
Taking advantage of this, I am using this snippet of code in one of my apps:
- (void)selectHostingAtIndex:(int)hostingIndex {
self.transitioning = YES;
UIViewController *garbageController = [[[UIViewController alloc] init] autorelease];
[self.navigationController pushViewController:garbageController animated:NO];
[self.navigationController popViewControllerAnimated:NO];
BBHostingController *hostingController = [[BBHostingController alloc] init];
hostingController.hosting = [self.hostings objectAtIndex:hostingIndex];
[self.navigationController pushViewController:hostingController animated:YES];
[hostingController release];
self.transitioning = NO;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
if (self.transitioning)
return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
else
return YES;
}
Basically, by creating an empty view controller, pushing it onto the stack, and immediately popping it off, it's possible to get the interface to revert to the portrait position. Once the controller has been popped, I just push on the controller that I intended to push in the first place. Visually, it looks great - the empty, arbitrary view controller is never seen by the user.
There is a simple way to programmatically force iPhone to the necessary orientation - using two of already provided answers by kdbdallas, Josh :
//will rotate status bar
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
//will re-rotate view according to statusbar
UIViewController *c = [[UIViewController alloc]init];
[self presentModalViewController:c animated:NO];
[self dismissModalViewControllerAnimated:NO];
[c release];
works like a charm :)
EDIT:
for iOS 6 I need to add this function:
(works on modal viewcontroller)
- (NSUInteger)supportedInterfaceOrientations
{
return (UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight);
}
I've been digging and digging looking for a good solution to this. Found this blog post that does the trick: remove your outermost view from the key UIWindow and add it again, the system will then re-query the shouldAutorotateToInterfaceOrientation: methods from your viewcontrollers, enforcing the correct orientation to be applied.
See it : iphone forcing uiview to reorientate
This is no longer an issue on the later iPhone 3.1.2 SDK. It now appears to honor the requested orientation of the view being pushed back onto the stack. That likely means that you would need to detect older iPhone OS versions and only apply the setOrientation when it is prior to the latest release.
It is not clear if Apple's static analysis will understand that you are working around the older SDK limitations. I personally have been told by Apple to remove the method call on my next update so I am not yet sure if having a hack for older devices will get through the approval process.
Josh's answer works fine for me.
However, I prefer posting an "orientation did change, please update UI" notification. When this notification is received by a view controller, it calls shouldAutorotateToInterfaceOrientation:, allowing you to set any orientation by returning YES for the orientation you want.
[[NSNotificationCenter defaultCenter] postNotificationName:UIDeviceOrientationDidChangeNotification object:nil];
The only problem is that this forces a re-orientation without an animation. You would need to wrap this line between beginAnimations: and commitAnimations to achieve a smooth transition.
Hope that helps.
FWIW, here's my implementation of manually setting orientation (to go in your app's root view controller, natch):
-(void)rotateInterfaceToOrientation:(UIDeviceOrientation)orientation{
CGRect bounds = [[ UIScreen mainScreen ] bounds ];
CGAffineTransform t;
CGFloat r = 0;
switch ( orientation ) {
case UIDeviceOrientationLandscapeRight:
r = -(M_PI / 2);
break;
case UIDeviceOrientationLandscapeLeft:
r = M_PI / 2;
break;
}
if( r != 0 ){
CGSize sz = bounds.size;
bounds.size.width = sz.height;
bounds.size.height = sz.width;
}
t = CGAffineTransformMakeRotation( r );
UIApplication *application = [ UIApplication sharedApplication ];
[ UIView beginAnimations:#"InterfaceOrientation" context: nil ];
[ UIView setAnimationDuration: [ application statusBarOrientationAnimationDuration ] ];
self.view.transform = t;
self.view.bounds = bounds;
[ UIView commitAnimations ];
[ application setStatusBarOrientation: orientation animated: YES ];
}
coupled with the following UINavigationControllerDelegate method (assuming you're using a UINavigationController):
-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
// rotate interface, if we need to
UIDeviceOrientation orientation = [[ UIDevice currentDevice ] orientation ];
BOOL bViewControllerDoesSupportCurrentOrientation = [ viewController shouldAutorotateToInterfaceOrientation: orientation ];
if( !bViewControllerDoesSupportCurrentOrientation ){
[ self rotateInterfaceToOrientation: UIDeviceOrientationPortrait ];
}
}
That takes care of rotating the root view according to whether an incoming UIViewController supports the current device orientation. Finally, you'll want to hook up rotateInterfaceToOrientation to actual device orientation changes in order to mimic standard iOS functionality. Add this event handler to the same root view controller:
-(void)onUIDeviceOrientationDidChangeNotification:(NSNotification*)notification{
UIViewController *tvc = self.rootNavigationController.topViewController;
UIDeviceOrientation orientation = [[ UIDevice currentDevice ] orientation ];
// only switch if we need to (seem to get multiple notifications on device)
if( orientation != [[ UIApplication sharedApplication ] statusBarOrientation ] ){
if( [ tvc shouldAutorotateToInterfaceOrientation: orientation ] ){
[ self rotateInterfaceToOrientation: orientation ];
}
}
}
Finally, register for UIDeviceOrientationDidChangeNotification notifications in init or loadview like so:
[[ NSNotificationCenter defaultCenter ] addObserver: self
selector: #selector(onUIDeviceOrientationDidChangeNotification:)
name: UIDeviceOrientationDidChangeNotification
object: nil ];
[[ UIDevice currentDevice ] beginGeneratingDeviceOrientationNotifications ];
This works for me (thank you Henry Cooke):
The aim for me was to deal with landscape orientations changes only.
init method:
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(orientationChanged:)
name:UIDeviceOrientationDidChangeNotification
object:nil];
- (void)orientationChanged:(NSNotification *)notification {
//[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
CGRect bounds = [[ UIScreen mainScreen ] bounds ];
CGAffineTransform t;
CGFloat r = 0;
switch ( orientation ) {
case UIDeviceOrientationLandscapeRight:
r = 0;
NSLog(#"Right");
break;
case UIDeviceOrientationLandscapeLeft:
r = M_PI;
NSLog(#"Left");
break;
default:return;
}
t = CGAffineTransformMakeRotation( r );
UIApplication *application = [ UIApplication sharedApplication ];
[ UIView beginAnimations:#"InterfaceOrientation" context: nil ];
[ UIView setAnimationDuration: [ application statusBarOrientationAnimationDuration ] ];
self.view.transform = t;
self.view.bounds = bounds;
[ UIView commitAnimations ];
[ application setStatusBarOrientation: orientation animated: YES ];
}
I have an app where I would like to support device rotation in certain views but other don't particularly make sense in Landscape mode, so as I swapping the views out I would like to force the rotation to be set to portrait.
I realise that the above original post in this thread is very old now, but I had a similar problem to it - ie. all of the screens in my App are portrait only, with the exception of one screen, which can be rotated between landscape and portrait by the user.
This was straightforward enough, but like other posts, I wanted the App to automatically return to portrait regardless of the current device orientation, when returning to the previous screen.
The solution I implemented was to hide the Navigation Bar while in landscape mode, meaning that the user can only return to previous screens whilst in portrait. Therefore, all other screens can only be in portrait.
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)pInterfaceOrientation {
BOOL lHideNavBar = self.interfaceOrientation == UIInterfaceOrientationPortrait ? NO : YES;
[self.navigationController setNavigationBarHidden:lHideNavBar animated:YES];
}
This also has the added benefit for my App in that there is more screen space available in landscape mode. This is useful because the screen in question is used to display PDF files.
Hope this helps.
I solved this quite easily in the end. I tried every suggestion above and still came up short, so this was my solution:
In the ViewController that needs to remain Landscape (Left or Right), I listen for orientation changes:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(didRotate:)
name:UIDeviceOrientationDidChangeNotification object:nil];
Then in didRotate:
- (void) didRotate:(NSNotification *)notification
{ if (orientationa == UIDeviceOrientationPortrait)
{
if (hasRotated == NO)
{
NSLog(#"Rotating to portait");
hasRotated = YES;
[UIView beginAnimations: #"" context:nil];
[UIView setAnimationDuration: 0];
self.view.transform = CGAffineTransformIdentity;
self.view.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(-90));
self.view.bounds = CGRectMake(0.0f, 0.0f, 480.0f, 320.0f);
self.view.frame = CGRectMake(0.0f, 0.0f, 480.0f, 320.0f);
[UIView commitAnimations];
}
}
else if (UIDeviceOrientationIsLandscape( orientationa))
{
if (hasRotated)
{
NSLog(#"Rotating to lands");
hasRotated = NO;
[UIView beginAnimations: #"" context:nil];
[UIView setAnimationDuration: 0];
self.view.transform = CGAffineTransformIdentity;
self.view.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(0));
self.view.bounds = CGRectMake(0.0f, 0.0f, 320.0f, 480.0f);
self.view.frame = CGRectMake(0.0f, 0.0f, 320.0f, 480.0f);
[UIView commitAnimations];
}
}
Keep in mind any Super Views/Subviews that use autoresizing, as the view.bounds/frame are being reset explicitly...
The only caveat to this method for keeping the view Landscape, is the inherent animation switching between orientations that has to occur, when it would be better to have it appear to have no change.
iOS 6 solution:
[[[self window] rootViewController] presentViewController:[[UIViewController alloc] init] animated:NO completion:^{
[[[self window] rootViewController] dismissViewControllerAnimated:NO completion:nil];
}];
The exact code depends per app and also where you place it (I used it in my AppDelegate). Replace [[self window] rootViewController] with what you use. I was using a UITabBarController.
I found a solution and wrote something in french (but code are in english). here
The way is to add the controller to the window view (the controller must possess a good implementation of the shouldRotate.... function).
If you are using UIViewControllers, there is this method:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
Return NO for the view controllers containing the views you don't want to rotate.
More info here
I don't think this is possible to do at run-time, though you could of course just apply a 90 degree transform to your UI.
This is what I use. (You get some compile warnings but it works in both the Simulator and the iPhone)
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];
Related
I've got a view controller listening for both UIKeyboardWillShowNotification and UIKeyboardWillHideNotification. The handlers for these notifications adjust various parts of the view, which is standard procedure.
The following code is used to convert the keyboard rect from screen coordinates:
CGRect keyboardBounds = [self.view convertRect:[keyboardBoundsValue CGRectValue] fromView:nil];
Again, standard procedure. Unfortunately, there is a critical situation where this conversion fails. Look at what happens when an iPhone is rotated from portrait to landscape while the keyboard is deployed:
1) iOS automatically fires UIKeyboardWillHideNotification; self.interfaceOrientation is reported as portrait; keyboardBounds.height is 216.0. This makes sense. Why? Because the notification handler is given the chance to "clean up" before the view switches to landscape mode.
2) iOS automatically fires UIKeyboardWillShowNotification; self.interfaceOrientation is reported as portrait; keyboardBounds.height is 480.0. This does NOT make sense. Why not? Because the notification handler is going to do its work thinking that the height of the keyboard is 480.0!
Did Apple drop the ball on this one, or am I doing something wrong?
Please note that listening instead for UIKeyboardDidShowNotification is not a valid solution, because it significantly degrades the user experience. Why? Because animating my changes to the view after the keyboard deployment animation occurs is... well, pretty terrible-looking.
Has anyone managed to get autorotation working perfectly while the keyboard is deployed? It seems like an explosion of chaos that Apple has completely overlooked. >:|
Maybe a bit late, but I've just run into the same issue and have a nice solution for it that avoids any kind of work arounds (unless of course apple change things)
Basically, when the notification center calls your method for UIKeyboardWillShowNotification (or any of the other notifications), the frame that it gives you for UIKeyboardFrameBeginUserInfoKey is in context of the window, NOT your view. The problem with this, is that the windows coordinate system is always in portrait, regardless of the devices orientation, hence you're finding the width and height the wrong way round.
If you want to avoid your work around, simply convert the rectangle into the coordinate system of your view (which does change according to the orientation). To do this, do something like the following :
- (void) keyboardWillShow:(NSNotification *)aNotification
{
CGRect keyboardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGRect convertedFrame = [self.view convertRect:keyboardFrame fromView:self.view.window];
......
/* Do whatever you want now with the new frame.
* The width and height will actually be correct now
*/
......
}
Hopefully this should be what you're after :)
Recently I've wrote a blog post about this exact problem you've described and how to solve it with a short and elegant way. Here is the link to the post: Synchronizing rotation animation between the keyboard and the attached view
If you don't want to dive into the long explanation described in the blog post here is a short description with a code example:
The basic principle is to use the same method that everyone uses - observing keyboard notifications to animate the attached view up and down. But in addition to that, you have to cancel these animations when the keyboard notifications are fired as a consequence of interface orientation change.
Rotation example without animation cancellation custom on interface orientation change:
Rotation example with animation cancellation on interface orientation change:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter]
addObserver:self selector:#selector(adjustViewForKeyboardNotification:)
name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self selector:#selector(adjustViewForKeyboardNotification:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter]
removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]
removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
self.animatingRotation = YES;
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
self.animatingRotation = NO;
}
- (void)adjustViewForKeyboardNotification:(NSNotification *)notification {
NSDictionary *notificationInfo = [notification userInfo];
// Get the end frame of the keyboard in screen coordinates.
CGRect finalKeyboardFrame = [[notificationInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
// Convert the finalKeyboardFrame to view coordinates to take into account any rotation
// factors applied to the window’s contents as a result of interface orientation changes.
finalKeyboardFrame = [self.view convertRect:finalKeyboardFrame fromView:self.view.window];
// Calculate new position of the commentBar
CGRect commentBarFrame = self.commentBar.frame;
commentBarFrame.origin.y = finalKeyboardFrame.origin.y - commentBarFrame.size.height;
// Update tableView height.
CGRect tableViewFrame = self.tableView.frame;
tableViewFrame.size.height = commentBarFrame.origin.y;
if (!self.animatingRotation) {
// Get the animation curve and duration
UIViewAnimationCurve animationCurve = (UIViewAnimationCurve) [[notificationInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
NSTimeInterval animationDuration = [[notificationInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// Animate view size synchronously with the appearance of the keyboard.
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:animationDuration];
[UIView setAnimationCurve:animationCurve];
[UIView setAnimationBeginsFromCurrentState:YES];
self.commentBar.frame = commentBarFrame;
self.tableView.frame = tableViewFrame;
[UIView commitAnimations];
} else {
self.commentBar.frame = commentBarFrame;
self.tableView.frame = tableViewFrame;
}
}
This answer was also posted in similar question: UIView atop the Keyboard similar to iMessage App
I met the same problem. iOS gaves me incorrect width/height of the keyboard. I used the following snipped in a keyboardDidShow handler:
CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGSize keyboardSize2 = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
LogDbg(#"keyboard size: frameBegin=%#; frameEnd=%#", NSStringFromCGSize(keyboardSize), NSStringFromCGSize(keyboardSize2));
and for portrait and landscape modes of iPad I got respectively:
2012-06-14 04:09:49.734 -[LoginViewController keyboardDidShow:] 132 [DBG]:keyboard size: frameBegin={768, 264}; frameEnd={768, 264}
2012-06-14 04:10:07.971 -[LoginViewController keyboardDidShow:] 132 [DBG]:keyboard size: frameBegin={352, 1024}; frameEnd={352, 1024}
Guessing that the width of the keyboard should be greater then the height (yep, i'm so naive) I made a workaround like following:
if (keyboardSize.width < keyboardSize.height)
{
// NOTE: fixing iOS bug: http://stackoverflow.com/questions/9746417/keyboard-willshow-and-willhide-vs-rotation
CGFloat height = keyboardSize.height;
keyboardSize.height = keyboardSize.width;
keyboardSize.width = height;
}
Well, try looking at keyboard width. If it is the value that you are expecting, then I assume that the values are simply switched ;). 480 makes sense as a keyboard width for going into landscape, which is what gives me this hunch.
If that fails, just store the portrait and landscape rectangles separately. They are well documented ;)
I know this a very very late reply. Now only I came on this situation and find the unanswered question. So I thought I'll share my solution. There will be some other better way, but the following way also we can solve this.
The KBKeyboardHandler that I used is from: UITextField: move view when keyboard appears
I just changed my delegate as following:
- (void)keyboardSizeChanged:(CGSize)delta
{
CGRect frame = self.view.frame;
UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
switch (interfaceOrientation) {
case UIInterfaceOrientationPortrait:
frame.origin.y-=delta.height;
break;
case UIInterfaceOrientationPortraitUpsideDown:
frame.origin.y+=delta.height;
break;
case UIInterfaceOrientationLandscapeLeft:
frame.origin.x-=delta.height;
break;
case UIInterfaceOrientationLandscapeRight:
frame.origin.x+=delta.height;
break;
default:
break;
}
self.view.frame = frame;
}
And it was working fine.
Here is my workaround:
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
float keyboardHeight = self.interfaceOrientation == UIInterfaceOrientationPortrait ? keyboardSize.height : keyboardSize.width;
Hope this helps :)
I use the following code to get the size of the keyboard which works fine for all rotations
NSDictionary *info = [aNotification userInfo];
if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation))
kbHeight = [[NSNumber numberWithFloat:[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.width] floatValue];
else
kbHeight = [[NSNumber numberWithFloat:[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.height] floatValue];
NSLog(#"keyboard height = %F",kbHeight);
I then test for the orientation using the status bar orientation (which works in the first launch case for the iPad) and shift the view in the relative direction needed to make space for the keyboard. This works perfectly, if the keyboard is visible then it relocates to the correct position on rotations.
UIDeviceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (orientation == UIDeviceOrientationPortrait)
{
NSLog(#"Orientation: portrait");
self.originalCenter = self.view.center;
self.view.center = CGPointMake(self.originalCenter.x, self.originalCenter.y-kbHeight);
}
if (orientation == UIDeviceOrientationPortraitUpsideDown)
{
NSLog(#"Orientation: portrait upside down");
self.originalCenter = self.view.center;
self.view.center = CGPointMake(self.originalCenter.x, self.originalCenter.y+kbHeight);
}
if (orientation == UIDeviceOrientationLandscapeLeft)
{
NSLog(#"Orientation: landscape left");
self.originalCenter = self.view.center;
self.view.center = CGPointMake(self.originalCenter.x+kbHeight,self.originalCenter.y);
}
if (orientation == UIDeviceOrientationLandscapeRight)
{
NSLog(#"Orientation: landscape right");
self.originalCenter = self.view.center;
self.view.center = CGPointMake(self.originalCenter.x-kbHeight,self.originalCenter.y);
}
You can return the view to its original position when the keyboard disappears or via a textFileDidEndEditing function.
I have an iAd which displays at the top of a fullscreen subview of the main view. The iAd works normally in portrait mode, and I have handled rotation of the iAd banner view into landscape mode. The issue occurs when the iAd is tapped by the user in landscape mode. The test advertisement displays in portrait, sideways on the phone, and when the user taps the x to dismiss the iAd, the banner view and its parent view are pushed offscreen. The iAd behaves normally in portrait mode (i.e. tapping it and closing it results in the view containing the banner to be displayed normally).
Things I have tried:
- (void)bannerViewActionDidFinish:(ADBannerView *)banner{
NSLog(#"Ad was closed, show the adView again");
if(UIInterfaceOrientationIsLandscape(currentInterfaceOrientation)){
[self animateRotationToLandscape:0.3f];
}
else{
[self animateRotationToPortrait:0.3f];
}
}
-(void)animateRotationToPortrait:(NSTimeInterval)duration{
self.adView.currentContentSizeIdentifier =
ADBannerContentSizeIdentifierPortrait;
BOOL iPad = NO;
#ifdef UI_USER_INTERFACE_IDIOM
iPad = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad);
#endif
if (iPad) {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:duration];
proUpgradeDescription.frame = CGRectMake(82,313,604,110);
proUpgradePrice.frame = CGRectMake(313,576,142,28);
closeButton.frame = CGRectMake(348,834,72,37);
purchaseButton.frame = CGRectMake(313,431,142,142);
[UIView commitAnimations];
}
else{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:duration];
proUpgradeDescription.frame = CGRectMake(20,80,280,70);
proUpgradePrice.frame = CGRectMake(88,322,142,28);
closeButton.frame = CGRectMake(123,403,72,37);
purchaseButton.frame = CGRectMake(88,172,142,142);
[UIView commitAnimations];
}
}
Which calls code that I use to animate rotation of the display for portrait and landscape mode. This code has no effect.
If anyone has any ideas as to why the test advertisements don't rotate correctly and why they push the parent view controller off the screen I would greatly appreciate it.
I don't know if this addresses all of your problems, but according to the answer on this question, the test ads are only in portrait, and real ads will show up in both orientations.
I know the question is a little old so I'm posting here just in case someone runs into the same problem (I did).
ADBannerView messes with the frame and transform properties of the parent view so all you have to do is to reset them to their original values after it has finished (in bannerViewActionDidFinish:).
I still don't understand why it doesn't put back everything the way it was after it has finished. We shouldn't have to do this.
This drove me nuts too. Delivering only landscape full page ads to the iPad and portrait to the iPhone and not saying so is asking for trouble. I gave up using the iAdSuite code, which caused the Landscape iPad ad to leave the screen in Landscape even when the device was in portrait!
This is my code for banner ads. It is all in the first view controller loaded. It aims to put the banner at the bottom of the screen.
In the header file:
#import "iAd/ADBannerView.h"
#property (strong, nonatomic) ADBannerView* adView;
#interface myViewController : UIViewController <ADBannerViewDelegate,
in viewDidLoad
CGRect contentFrame = self.view.bounds;
CGRect bannerFrame = CGRectZero;
bannerFrame.size = [adView sizeThatFits:contentFrame.size];
bannerFrame.origin.y = contentFrame.size.height-bannerFrame.size.height;
adView = [[ADBannerView alloc] initWithFrame:bannerFrame];
[adView setDelegate:self];
[self.view addSubview:adView];
Then
-(void)viewWillLayoutSubviews {
CGRect contentFrame = self.view.bounds;
CGRect bannerFrame=CGRectZero;
bannerFrame.size = [adView sizeThatFits:contentFrame.size];
if (adView.bannerLoaded) {bannerFrame.origin.y = contentFrame.size.height-bannerFrame.size.height;}
else {bannerFrame.origin.y = contentFrame.size.height;}
[adView setFrame:bannerFrame];}
Then to handle the callbacks from iAd we need to tell the view to redo its layout if something changes:
- (void)bannerViewDidLoadAd:(ADBannerView *)banner{
[UIView animateWithDuration:0.25 animations:^{
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
}];}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error{
[UIView animateWithDuration:0.25 animations:^{
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
}];}
This seems to handle the orientation correctly on both iPad and iPhone except for the test full page ads. However, the screen assume correct orientation after the test ad is dismissed so I am hoping it is all OK.
I am building an application with multiple UIViewControllers controlled by a RootViewController. Currently in the plist the application defaults to LandscapeRight.
Lets say I have the following files that can be loaded into the RootViewController:
IntroView (Landscape Right ONLY)
LandscapeView (Landscape Right ONLY)
PortraitView (Portrait ONLY)
I also added into the RootViewController's shouldAutorotateToInterfaceOrientation the following:
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
if ([currentClass class] == PortraitView.class) {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
} else {
return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
}
so all is well until I load in the PortraitView and in the viewWillAppear i add the following (similar to this thread
if (self.interfaceOrientation == UIInterfaceOrientationPortrait) { //UIInterfaceOrientationLandscapeRight) {
self.view.transform = CGAffineTransformIdentity;
self.view.transform = CGAffineTransformMakeRotation(degreesToRadian(-90));
self.view.bounds = CGRectMake(0.0, 0.0, 320, 480);
self.view.center = CGPointMake(240.0f, 160.0f);
}
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait];
This yields a properly loaded in PortraitView but now my issue is that within my PortraitView I have 2 subviews that I would like to flip between, but because I rotated my view UIViewAnimationTransitionFlipFromLeft actually makes it flip top to bottom instead of left to right. I cannot for the life of me figure out how to tell PortraitView that its in Portrait.
When I check [[UIDevice currentDevice] orientation]; it tells me its in Landscape. When I attempt to use shouldAutorotateToInterfaceOrientation and set it to Portrait only it will then rotate my view so it is no longer correct.
Hopefully this makes sense! Been looking at this issue all day.
Thanks!
I ran into this slightly differently; a UIViewController subclass in landscape mode that swapped top-to-bottom instead of left-to-right.
The fix that worked for me was to add all my views to a single “inner” view and then flip that instead of the UIViewController’s normal view.
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight
forView:[self innerView]
cache:YES];
Where [self innerView] is the sole child of [self view], and all the subviews are inside of it.
How do I change or disable the rotating animation when screen orientation changes from landscape to portrait, or vice versa?
Yes, it is possible to disable the animation, without breaking everything apart.
The following codes will disable the "black box" rotation animation, without messing with other animations or orientation code:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[UIView setAnimationsEnabled:YES];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
[UIView setAnimationsEnabled:NO];
/* Your original orientation booleans*/
}
Place it in your UIViewController and all should be well. Same method can be applied to any undesired animation in iOS.
Best of luck with your project.
If you dont want your view controllers to rotate just override the shouldAutoRotateToInterface view controller method to return false for whichever orientation you dont want to support...Here is a reference.
In the case that u just want to handle rotation some other way, you can return false in the above methods and register for UIDeviceOrientationDidChangeNotification like so
NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:#selector(handleOrientationDidChange:)
name:UIDeviceOrientationDidChangeNotification
object:nil];
Now when u get the notifications u can do whatever you want with it...
The answer by #Nils Munch above is find for < iOS7. For iOS 7 or later you can use:
- (void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[UIView setAnimationsEnabled:NO];
[coordinator notifyWhenInteractionEndsUsingBlock:^(id<UIViewControllerTransitionCoordinatorContext> context) {
[UIView setAnimationsEnabled:YES];
}];
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
}
I'm having a real issue with UITabBarController.
The outcome I'm after is the following:
1) in portrait mode, a simple tab bar based application (with navigation bars) nothing too fancy.
2) in landscape mode, I want to use my own UIViewController ignoring the UITabBar completely.
The approach (I tried many variants) I tried last which I fail to understand why is not "working" is the following:
I have a custom UIViewController (Call this AA) that is suppose to manage "everything".
This controller is added to the window in application start and in its loadView creates two controllers: a UITabBarController (Call this TBC) and a UILandscapeController (Call this LSC). then I add the tabbarcontroller view as a subview of AA's view.
now in AA class I override the didRotate blah or willRotate blah and basically want to switch between the two views, by this I means something like: (pseudo code):
going from portrait to landscape:
[TBC.view removeFromSuperView];
[AA.view addSubview:LSC.view];
and when returning to portrait reverse it.
[LSC.view removeFromSuperView];
[AA.view addSubview:TBC.view];
The amount of problems I have (well, it simple rotates wrongly creating a real messed up interface) are something completely unexplained. It seems like the tabbarcontroller view does not "like" at all to be in the standard view heirarchy but rather it wants to be attached directly to the screen.
I wonder what is the best approach to achieve my goal and why the tabbar does not like to be a subview of a view,
any hints mostly appreciated.
-t
Just in case you still need the answer, or someone else stumbles onto this, I've done the same thing and got it working, but there are a couple of hoops you have to jump through. In order to rotate a UITabBarController's view, there are four things you have to do:
Remove the status bar before switching to the view
Rotate the view to the new frame
Add the status bar back to the view
Switch to the view.
I've got a RootRotationController that does this that looks like this:
#implementation RootRotationController
#define degreesToRadian(x) (M_PI * (x) / 180.0)
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
if ((UIInterfaceOrientationPortrait == interfaceOrientation) || (UIInterfaceOrientationPortraitUpsideDown == interfaceOrientation)) {
[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];
}
// Return YES for supported orientations
return YES;
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
[super willAnimateRotationToInterfaceOrientation:interfaceOrientation duration:duration];
if (UIInterfaceOrientationLandscapeLeft == interfaceOrientation) {
self.view = self.landscape.view;
self.view.transform = CGAffineTransformIdentity;
self.view.transform = CGAffineTransformMakeRotation(degreesToRadian(-90));
self.view.bounds = CGRectMake(0, 0, 480, 300);
} else if (UIInterfaceOrientationLandscapeRight == interfaceOrientation) {
self.view = self.landscape.view;
self.view.transform = CGAffineTransformIdentity;
self.view.transform = CGAffineTransformMakeRotation(degreesToRadian(90));
self.view.bounds = CGRectMake(0, 0, 480, 300);
} else if (UIInterfaceOrientationPortrait == interfaceOrientation) {
mainInterface.view.transform = CGAffineTransformIdentity;
mainInterface.view.transform = CGAffineTransformMakeRotation(degreesToRadian(0));
mainInterface.view.bounds = CGRectMake(0, 0, 300, 480);
[[UIApplication sharedApplication] setStatusBarHidden:NO animated:NO];
self.view = mainInterface.view;
} else if (UIInterfaceOrientationPortraitUpsideDown == interfaceOrientation) {
mainInterface.view.transform = CGAffineTransformIdentity;
mainInterface.view.transform = CGAffineTransformMakeRotation(degreesToRadian(180));
mainInterface.view.bounds = CGRectMake(0, 0, 300,480);
[[UIApplication sharedApplication] setStatusBarHidden:NO animated:NO];
self.view = mainInterface.view;
}
}
In addition, you should know that shouldAutorotateToInterfaceOrientation is called just after adding the root controller's view to the window, so you'll have to re-enable the status bar just after having done so in your application delegate.
Your problem comes from the typo, I think. Change removeFromSuperView to removeFromSuperview.
Though, it still has a problem. Tab bar doesn't rotate properly. It go upwards till it disappers.
How about not removing the tab bar, and make it transparent.
Check out the UIViewController instance method rotatingFooterView in the docs.
Or, you may manage TabBar by yourself, not through the UITabBarController.