试图在方向改变时加载新的视图

我试图在Xcode中创build一个应用程序,当手机从一个方向旋转到另一个方向时,将切换到新的视图。

这里是“switchviewcontroller.h”文件代码:

#import <UIKit/UIKit.h> @interface SwitchViewController : UIViewController { } -(IBAction)switchview:(id)sender; @end 

这里是“switchviewcontroller.m”文件代码:

 #import "SwitchViewController.h" #import "secondview.h" @implementation SwitchViewController -(IBAction)switchview:(id)sender {} // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return YES; } - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { if((fromInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (fromInterfaceOrientation == UIInterfaceOrientationLandscapeRight)) { [[secondview alloc] initWithNibName:@"secondview" bundle:[NSBundle mainBundle]]; } } 

它运行在iPhone模拟器没有错误,但是,当我旋转它不会加载新的观点。 对于初学者,我认为我需要应用程序以横向模式打开,我不知道该怎么做,但它仍然无法工作,我认为它与代码中的“initWithNibName”部分有关我有.xib文件,而不是.nib文件。 任何人都可以帮助我这两件事? 谢谢。

你不是推动或呈现任何东西,你只是在启动视图。

 secondview *second = [[secondview alloc] initWithNibName:@"secondview" bundle:[NSBundle mainBundle]]; [self.navigationController pushViewController:second animated:YES]; 

但是,它并不是一个展现新观点的好地方。

如果您想以不同的方向显示相同的视图,请尝试以下操作:

 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { if(((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight))){ self.view = landscape; }else if(((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))){ self.view = portrait; } return YES; } 

请注意, portraitlandscape是您的UIViewController中的UIViews,您在您的头文件中定义并通过Interface Builder进行连接。


另外,这些需要在.h / .m中

。H

 IBOutlet UIView *portrait; IBOutlet UIView *landscape; @property(nonatomic,retain) UIView portrait; @property(nonatomic,retain) UIView landscape; 

.M

 @synthesize portrait,landscape; 

你必须分配和初始化一个新的视图,并用新的视图replace你当前的视图控制器的视图。

 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation) { UIView *landscapeView = [[UIView alloc] init]; // Setup the landscape view here self.view = landscapeView; [landscapeView release]; } else { UIView *portraitView = [[UIView alloc] init]; // Setup the portrait view here self.view = portraitView; [portraitView release]; } }