我正在尝试在Xcode中创建一个应用程序,当手机从一个方向旋转到另一个方向时,该应用程序将切换到新视图。
这是“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文件。任何人都可以帮我这两件事吗?感谢。
答案 0 :(得分:5)
你没有推动或展示任何东西,你只是在开始观察。
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;
}
请注意,portrait
和landscape
是UIViewController中的UIView,您可以在标头中定义并通过Interface Builder进行连接。
另外,这些需要在 .h / .m :
IBOutlet UIView *portrait;
IBOutlet UIView *landscape;
@property(nonatomic,retain) UIView portrait;
@property(nonatomic,retain) UIView landscape;
@synthesize portrait,landscape;
答案 1 :(得分:2)
您必须分配并初始化一个新视图,并用新视图替换当前的viewcontroller视图。
- (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];
}
}