My code goes like this:
- (void)viewDidLoad
{
[self setGridView];
}
-(void)setGridView
{
CGRect frame;
frame .origin.x=0;
frame.origin.y=20;
frame.size.width=GRID_WEIGHT;
frame.size.height=GRID_HEIGHT;
GridView *ObjGridView=[[GridView alloc]initWithFrame:frame];
[[NSBundle mainBundle ] loadNibNamed:#"GridView" owner:ObjGridView options:nil];
[ObjGridView setGridViewFrame:frame];
[self.view addSubview:ObjGridView.GridCellView];
frame .origin.x+=GRID_WEIGHT;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
This code adds a subview to a view and sets the frame
My problem:
1-How do i refresh my view when Orientation(landscape or portrait) happens,
because i set the frame of subview in the lanscape mode and i wants to use the sane view in my portrait view also .(basically where do i call this -(void)setGridView delegate method)?
2-How do i know, my subview exceeding the bound of the view,so that i can handle the subview in my setGridView method ?
1.Below method will call automatically whenever your orientation changes. Do the necessary changes according to each orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
if (interfaceOrientation == UIInterfaceOrientationPortrait) {}
else if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {}
else if (interfaceOrientation == UIInterfaceOrientationLandscapeRight) {}
else if (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {}
return YES;
}
2.You should know the width and height of your views and set the frames accordingly. That is not a big deal.
Hope this is helpful.
I am learning the ins and outs of iOS Application development myself, so please forgive me for the brevity of my response.
I believe you may be able to find the answer to your issue within the section titled 'Responding to Orientation Changes' within this document on Apple's Developer Resources:
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/RespondingtoDeviceOrientationChanges/RespondingtoDeviceOrientationChanges.html
I hope this helps you deduce a resolution to your issue.
In viewDidLoad
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(OrientationChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
Method for notify you that Orientation Changed:-
-(void)OrientationChange:(NSNotification*)notification
{
UIDeviceOrientation Orientation=[[UIDevice currentDevice]orientation];
if(Orientation==UIDeviceOrientationLandscapeLeft || Orientation==UIDeviceOrientationLandscapeRight)
{
NSLog(#"Landscape");
}
else if(Orientation==UIDeviceOrientationPortrait)
{
NSLog(#"Portrait");
}
}
In response to your questionsL
With regard to resizing on orientation change:
If you set your springs and struts accordingly it should autoresize automatically, alternatively you can do this in code as per deamonsarea's answer
To check if a view is exceeding the bounds of the superview use CGRectContainsRect
something like.
CGRect frame0 = self.view.bounds;
CGRect frame1 = ObjGridView.frame;
if(CGRectContainsRect(frame0,frame1)==NO){
NSLog(#"exceeds bounds")
}
Also noticed you are not calling [super viewDidLoad] and this line
[[NSBundle mainBundle ] loadNibNamed:#"GridView" owner:ObjGridView options:nil];
loads a new instance of the view but you are not refering to it anywhere
I found this question while looking for a way to react to orientation change inside the UIView itself. In case anyone else comes along...
If you want to react to orientation change inside a UIView, rather than a UIViewController (for encapsulation or other reasons), you can use this method:
class MyView: UIView {
override func layoutSubviews() {
super.layoutSubviews()
println("orientation or other bounds-impacting change")
}
}
Related
Problem: A have an App that uses both Landscape mode (locked) and Portrait Mode (locked) for different parts of the app. Now I have a working solution however it doesn't seem correct and does have it's own problems.
Optimally I would love to force a orientation change. Thinking even about doing a view transformation if needed.
Basic flow of App:
HomeView (Portrait) (which has a few sub pushed views that are also portrait and locked to that).
LandscapeView (Landscape) (which has 5 pushed subviews that are also landscape)
Note:
HomeView has a link to LandscapeView
LandscapeView can go back to HomeView
At the end of the LandscapeView subviews it returns to the HomeView
Basic Image showing how this looks with the different view orientations. (The lines indicate flow of app, orientation of the images indicate how each screen should be )
Currently using the below implementation to call / set if the view is in portrait mode or landscape mode by [setLockedToPortait:YES] (for portrait view) etc.
This in term makes the query for what interface orientation to use from iOS if the device is rotated.
Now for the case of going to the LandscapeView, I show a temporary view over the top of the normal view asking to use to rotate their phone to landscape. (A temporary view is also shown when returning to the HomeView from a landscape view)
So once the user has rotated their device, it will trigger the correct orientation and then the temporary view will hide.
If the user then rotates their phone back to portrait at this point it will still be locked to landscape so will not trigger another view rotation (also no temp view will appear or anything)
Current Implementation Code::
// ---------------------- NavigationController (subclass of UINavigationController)
#interface NavigationController () {
BOOL isOrientationPortrait;
}
#end
#implementation NavigationController {
UIDeviceOrientation lastAccepted;
UIDeviceOrientation lastKnown;
}
-(void)setLockedToPortait:(BOOL)isLocked {
isOrientationPortrait = isLocked;
}
-(UIDeviceOrientation) getCurrentOrientation {
UIDeviceOrientation orientate = [[UIDevice currentDevice] orientation];
if(orientate == 0) { // needed for simulator
orientate = (UIDeviceOrientation)[UIApplication sharedApplication].statusBarOrientation;
}
return orientate;
}
// Deprecated in iOS6, still needed for iOS5 support.
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)toInterfaceOrientation
{
UIDeviceOrientation orientation = [self getCurrentOrientation];
[self setLastKnownOrientation:orientation];
if(isOrientationPortrait == YES) {
if([self isLastKnownPortrait] == YES) {
[self setLastAcceptedOrientation:orientation];
return YES;
} else {
return NO;
}
} else {
if([self isLastKnownLandscape] == YES) {
[self setLastAcceptedOrientation:orientation];
return YES;
} else {
return NO;
}
}
}
// iOS6/7 support
- (BOOL)shouldAutorotate
{
// find out the current device orientation
UIDeviceOrientation orientation = [self getCurrentOrientation];
[self setLastKnownOrientation:orientation];
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
if(isOrientationPortrait == YES) {
if([self isLastKnownPortrait] == YES)
{
UIDeviceOrientation orientation = [self getCurrentOrientation];
[self setLastAcceptedOrientation:orientation];
}
return (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown);
} else {
if([self isLastKnownLandscape] == YES)
{
UIDeviceOrientation orientation = [self getCurrentOrientation];
[self setLastAcceptedOrientation:orientation];
}
return (UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight );
}
}
-(void)setLastAcceptedOrientation:(UIDeviceOrientation)orient {
lastAccepted = orient;
}
-(void)setLastKnownOrientation:(UIDeviceOrientation)orient {
lastKnown = orient;
}
-(BOOL)isLastKnownPortrait {
return UIDeviceOrientationIsPortrait(lastKnown);
}
-(BOOL)isLastKnownLandscape {
return UIDeviceOrientationIsLandscape(lastKnown);
}
-(BOOL)isLastAcceptedPortrait {
return UIDeviceOrientationIsPortrait(lastAccepted);
}
-(BOOL)isLastAcceptedLandscape {
return UIDeviceOrientationIsLandscape(lastAccepted);
}
Current Problems:
Device rotations are always required after a view has loaded for the user going to Landscape mode from Portrait and vice versa.
If the user has the device orientation locked, this will not work at all.
When transitioning back from Landscape mode, and the user has already rotated their device to Portrait (in the last landscape view), the Portrait view's interface will be locked to a 'Landscape' layout until the user re-rotates their device (so currently I am just showing the overlay to rotate the device, but it is already rotated… very annoying for the user). Massive issue right now with the above implementation.
Would love to be able to:
Force an orientation change on the phone for the current view.
Set a preferred layout for a view which is forced between push/pops of views.
I've looked a lot at the other solutions on here and on the Apple Dev forums, however none seem to cover this problem, or still this orientation bug between the two views exists as well.
Thanks for any help or pointers! No advice will be discounted :D
--
Edit::
Solution Found thanks to #leo-natan!!
So instead of trying to force a change of orientation on the views. Just push a new modal view. This forces a change. You still need to above orientation code for managing rotations.
So what I have now in my HomeViewController:
LandscapeViewController * viewController = [[[LandscapeViewController ViewController alloc] init] autorelease];
UINib * nib = [UINib nibWithNibName:#"NavigationController" bundle:nil];
NavigationController *navController = [[nib instantiateWithOwner:nil options:nil] objectAtIndex:0];
[navController initWithRootViewController:viewController];
[self presentViewController:navController animated:YES completion:^{
// completion
}];
So it is necessary to re-add a new navigation controller for this modal view. Also note above 'presentViewController' is the new way of pushing Modal views.
Implemented this overloaded method for the managing of the view controller:
-(id)initWithRootViewController:(UIViewController *)rootViewController {
self = [super initWithRootViewController:rootViewController];
if(self){
}
return self;
}
Note: The above is not using storyboards. The problem may be solved by using storyboards and modally showing a view in the same fashion.
See my answer here, including a test project.
Basically, orientation can only be forced to change when presenting a view controller modally. For example, media playback in some apps. If you wish to transition from a view controller that can only be presented in portrait to a view controller that is only presented in landscape, you will need a modal presentation. Push will not work.
I want to change the orientation of the app without changing the device orientation in iphone app.
I want to change my view from portraid mode to landscap mode programmatically.
And also want to know that will this be accepted by the apple store or not ?
Thanks
Now I got the solution from other that is as follow
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];
when you add this line at that time one warning appear and for remove this warning just add bellow code on you implementation file..
#interface UIDevice (MyPrivateNameThatAppleWouldNeverUseGoesHere)
- (void) setOrientation:(UIInterfaceOrientation)orientation;
#end
and after that in bellow method just write this code if required..
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
But now want to know is this accepted by apple app store or not ?
thanks
use this line for programmatically change orientation...
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];
and also when you add this line at that time one warning appear and for remove this warning just add bellow code on you implementation file..
#interface UIDevice (MyPrivateNameThatAppleWouldNeverUseGoesHere)
- (void) setOrientation:(UIInterfaceOrientation)orientation;
#end
and after that in bellow method just write this code if required..
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
// return NO;
return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
i hope this help you..
:)
Add a class variable
Bool isInLandsCapeOrientation;
in viewDidLoad
set this flag to
isInLandsCapeOrientation = false;
Add the following function
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if (!isInLandsCapeOrientation) {
return (UIInterfaceOrientationIsPortrait(interfaceOrientation));
}else {
return (UIInterfaceOrientationIsLandscape(interfaceOrientation));
}
}
To changing orientation from portrait to landscape, let it happens on a button action
- (IBAction)changeOrientationButtonPressed:(UIButton *)sender
{
isInLandsCapeOrientation = true;
UIViewController *viewController = [[UIViewController alloc] init];
[self presentModalViewController:viewController animated:NO];
[self dismissModalViewControllerAnimated:NO];
}
This works fine for me.
To change Orientation portraid mode to landscap mode use this code
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
use this code for programmatically change orientation...
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];
If you want to change the particular view only in landscape..then u can try the following in its viewDidLoad
float angle = M_PI / 2;
CGAffineTransform transform = CGAffineTransformMakeRotation(angle);
[ [self.view] setTransform:transform];
The documentation describes the orientation property as being read-only, so if it works, I'm not sure you can rely on it working in the future (unless Apple does the smart thing and changes this; forcing orientation changes, regardless of how the user is currently holding their device, is such an obvious functional need).
As an alternative, the following code inserted in viewDidLoad will successfully (and somewhat curiously) force orientation (assuming you've already modified you shouldAutorotateToInterfaceOrientation ):
if (UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]))
{
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
UIView *view = [window.subviews objectAtIndex:0];
[view removeFromSuperview];
[window addSubview:view];
}
Clearly, this does it if the user is currently holding their device in portrait orientation (and thus presumably your shouldAutorotateToInterfaceOrientation is set up for landscape only and this routine will shift it to landscape if the user's holding their device in portrait mode). You'd simply swap the UIDeviceOrientationIsPortrait with UIDeviceOrientationIsLandscape if your shouldAutorotateToInterfaceOirentation is set up for portrait only.
For some reason, removing the view from the main window and then re-adding it forces it to query shouldAutorotateToInterfaceOrientation and set the orientation correctly. Given that this isn't an Apple approved approach, maybe one should refrain from using it, but it works for me. Your mileage may vary. But this also refers to other techniques, too. Check
SO discussion
What I am having so far is
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
NSLog(#"willAnimateRotationToInterfaceOrientation");
if(toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
NSLog(#"PortraitUpsideDown");
// Do method A
} else {
[[self.view subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
// Do method B
}
}
and
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
NSLog(#"didRotateFromInterfaceOrientation");
if( fromInterfaceOrientation == UIInterfaceOrientationPortrait || fromInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown){
NSLog(#"OrientationPortrait or PortraitUpsideDown");
[[self.view subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
// Do method B
} else {
NSLog(#"From else");
[[self.view subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
// Do method A
}
}
My logic is after hitting the RUN from xcode, willAnimateRotationToInterfaceOrientation: is going to be called because I set Supported Device Orientation to be UpsideDown from Summary of MyApp.xcodeproj. Moreover, I also think that didRotateFromInterfaceOrientation: should not be called because we have just started the app yet. It means there are no previous states at all.
Unfortunately, this is what I got after doing the debugger
2012-02-11 12:04:08.776 MyApp[7505:10703] willAnimateRotationToInterfaceOrientation :
2012-02-11 12:04:08.776 MyApp[7505:10703] PortraitUpsideDown
2012-02-11 12:04:08.778 MyApp[7505:10703] didRotateFromInterfaceOrientation :
2012-02-11 12:04:08.779 MyApp[7505:10703] OrientationPortrait or
PortraitUpsideDown
I am getting lost now. Does anyone have any ideas about the issue, please help. Thanks.
I have had some issues with rotation, similar to yours. The short version is that the will and did methods are not 100% reliable. You should try rapidly rotating back and forth and see what happens. It could be because I am pretty new, or it could be an actual bug. What I did was, in didRotateFromInterfaceOrientation:, check the current orientation and act accordingly:
if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation) {
// do your portrait stuff
} else {
// do your landscape stuff
}
Before I found the UIInterfaceOrientationIsPortait test I was actually checking the frame to see if self.view.frame.size.width > self.view.frame.size.height, and that is also reliable but kind of ugly.
Either way is reliable. I have a couple apps in the store, QPalettes and QColor, that do rotation on a bunch of user-created onscreen elements. What I had to do is store the dimensions, and after didRotateFromInterfaceOrientation I check the new dimensions and if they are different, re-draw everything onscreen. Contact me if you'd like a promo code to check out the rotation in either app (they rotate the same - QColor is more complex since it also draws intersections).
Enjoy,
Damien
I have spent the last several hours trying to get this to work and I can't so I need to know if what I am trying to do is the correct thing. Its driving me mad!
My goal is to have a ViewController that detects orientation change. When it's portrait it shows a view with a UITableView, when its landscape it shows a UIView with content that I will programmatically create.
In my parent viewcontroller I have:
- (void)viewDidLoad
{
[super viewDidLoad];
TableDataViewController *tableDataController = [[TableDataViewController alloc]
initWithNibName:#"TableDataViewController"
bundle:nil];
self.tableDataViewController = tableDataController;
[self.view insertSubview: tableDataController.view atIndex:0];
[tableDataController release];
}
This loads my view containing the table view and the controller that goes with it. The user then rotates the device and the function:
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toOrientation
duration:(NSTimeInterval)duration
{
if (toOrientation == UIInterfaceOrientationPortrait) {
NSLog(#"PerformAnalysisViewController: Gone to Potrait");
}
if ((toOrientation == UIInterfaceOrientationLandscapeLeft) ||
(toOrientation == UIInterfaceOrientationLandscapeRight)) {
NSLog(#"PerformAnalysisViewController: Gone to Landscape");
// Load new view here
CGRect frame = [[UIScreen mainScreen] applicationFrame];
UIView *horizView = [[[HorizView alloc]
initWithFrame:frame] autorelease];
[self setView:horizView];;
}
}
will trigger depending. However it doesn't trigger? Is this because control has passed to the Subview I have inserted in the viewDidLoad? If so how do I get it back? Do I have to get it to detect orientation and then remove itself from the superview?
If that was then working would the new view be added as I have it above? I have tried reading the Apple documentation but I can't make this work.
All help greatly appreciated.
Mike
I am using the willRotateToInterfaceOrientation method in order to handle UI rotation:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
if( interfaceOrientation == UIInterfaceOrientationPortrait ||
interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown ) {
self.backgroundImageView.image = [UIImage imageNamed:#"vertical.png"];
}
else {
self.backgroundImageView.image = [UIImage imageNamed:#"horizontal.png"];
}
}
Please check, that your Info.plist supports more than one orientation and that you have implemented shouldAutorotateToInterfaceOrientation:interfaceOrientation by returning YES.
As the title says. My UIViewController will not rotate no matter what. When it loads shouldAutorotateToInterfaceOrientation is being called but after that it doesnt.
UPDATE 1:
It's a really really wierd problem. At least for me. And i ll try to explain everything.
It's a navigation based app. Every controller has
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
return YES;
}
Xcontroller is a child of Acontroller and it doesn't auto rotate. If Xcontroller become a child of Bcontroller then it will autorotate. So something is wrong with Acontroller. But Acontroller is identical (except its data) to Bcontroller.
Whats Wrong?
UPDATE 2:
I decided to recreate Acontroller. And it worked.I believe I was missing something stupid.
I am not sure whether it's the same reason as your case. But I experienced the same thing. the shouldAutorotateToInterfaceOrientation was only called once in the beginning.
After some serious debugging by taking code apart, I found that the reason is in my overridden init method.
I had this before:
- (id)initWithAlbum:(PhotoAlbum *)theAlbum {
if (self) {
self.photoAlbum = theAlbum;
}
return self;
}
And then I changed to this
- (id)initWithAlbum:(PhotoAlbum *)theAlbum {
if (self = [super init]) {
self.photoAlbum = theAlbum;
}
return self;
}
Note: the only difference is I added [super init] to call the parent init.
After this change, the rotation works well and the shouldAutorotateToInterfaceOrientation is being called everytime I rotate the screen.
Hope this help.
There can be several possible reasons your view controller does not rotate.
See Apple's official Q&A on this issue:
Why won't my UIViewController rotate with the device?
http://developer.apple.com/library/ios/#qa/qa2010/qa1688.html
Apple Q&A has the detailed solution for the problem.
Why won't my UIViewController rotate with the device?
http://developer.apple.com/library/ios/#qa/qa1688/_index.html
If you add a viewcontroller.view to uiwindow, you should set this viewcontroller as rootviewcontroller.
[self.window addSubview: mainViewcontroller.view];
self.window.rootViewController=mainViewcontroller;
Also, make sure you don't have rotation lock on. I spent a good hour trying to figure out why my views stopped rotating. shouldAutorotateToInterfaceOrientation was being called only once at start up and when Game Center leaderboards/achievements were presented.
I had the same issue - the reason was, that it was my first UIViewController, that i created on the fly in my ApplicationDelegate, added it's View to my UIWindow and immediately released it.
That's of course not correct as I just added the UIView of the UIViewController (retaining it) and than released the whole controller.
You should add your first UIViewController as an instance variable in Your ApplicationDelegate instead, and release it in Your ApplicationDelegate's dealloc-method.
In my case, the ViewController was inside a NavigationController which was used by a "parent" viewControlled that received the orientation changes.
What I did in this parent was:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
if(_navigationController){
return [_navigationController.topViewController shouldAutorotateToInterfaceOrientation: toInterfaceOrientation];
}
return toInterfaceOrientation == UIInterfaceOrientationPortrait;
}
This way you can implement your own orientation change logic depending on the currently visible controller.
(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{ return YES; }
The above method if u using, you will able to call many time if u want with out any error.
I think there is no strange behavior here, it is called only one which is right. There is no need to call more than one to decide if the device should rotate to a direction or not.
This method just ask if the device should rotate to a direction or not.
If you want to handle the orientation change, you should register for the notification from the UIDeviceDidChangeOrientationNotification and override the following method:
- (void)orientationChanged:(NSNotification *)notification
{
UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
if (UIDeviceOrientationIsLandscape(deviceOrientation) &&
!isShowingLandscapeView)
{
[self presentModalViewController:self.landscapeViewController
animated:YES];
isShowingLandscapeView = YES;
}
else if (deviceOrientation == UIDeviceOrientationPortrait &&
isShowingLandscapeView)
{
[self dismissModalViewControllerAnimated:YES];
isShowingLandscapeView = NO;
}
}
See more here.
I have the same problem but with two view controllers added to the application's UIWindow. The reason
is The view controller's UIView property is embedded inside UIWindow but alongside an additional view controller
From Apple Technical Q&A
http://developer.apple.com/library/ios/#qa/qa1688/_index.html