由于横竖屏切换的问题,视图里面的子视图不响应切换事件,这样就会很麻烦,所以如果把子视图转为根视图就可以响应这个事件
经过一晚上的研究,终于解决了这个问题;
问题1:在视图里添加一个根视图,个人理解根视图就是在window下的视图
DetailController *DetailController=[[[DetailController alloc]initWithNibName:@"DetailController" bundle:nil]autorelease];
self.view.window.rootViewController=DetailController;
这个代码很不完备,比如存在内存泄漏,需要这样:
DetailController *detailController=[[[DetailController alloc] initWithNibName:@"DetailController" bundle:nil] autorelease];
因为,这个detailController这句话后,计数器为1了,再赋值给window.rootViewController属性,就是2了。因此这里要做自动释放。
问题2
这个代码还有个问题,就是看上去很别扭,在一个控制器代码里去创建另一个控制器。这一方面很容易出问题,另一方面,代码的结构不清晰。
所以这里就用到了delegate来实现实图的切换
第一步:新建一个SwitchViewDelegate.h
#import <UIKit/UIKit.h>
@protocol SwitchViewDelegate
/实现视图的切换,以后每次要切换到根视图,就在这里加入相应的函数就可以
-(void)getfengmian;
@end
第二步:这里是我的应用文件 myvacationAppDelegate.h
#import <UIKit/UIKit.h>
#import "myvacationViewController.h"
#import "SwitchViewDelegate.h" //引入委托头文件
@class myvacationViewController;
@interface myvacationAppDelegate : NSObject<UIApplicationDelegate,SwitchViewDelegate> {
UIWindow *window;
myvacationViewController *viewController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet myvacationViewController *viewController;
@end
第三步:myvacationAppDelegate.m
#import "myvacationAppDelegate.h"
#import "fengmian.h";
@implementation myvacationAppDelegate
@synthesize window;
@synthesize viewController;
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//初使化添加一个默认view,也就是你程序启动的第一个view
[self.window addSubview:viewController.view];
//设置委托,必不可少的哦
viewController.delegate=self;
[self.window makeKeyAndVisible];
return YES;
}
//实现视图的切换,以后每次要切换到根视图,就在这里加入相应的函数就可以,函数内容如下
-(void)getfengmian{//切换到封面视图
fengmian *fengmiancontroller=[[fengmian alloc] initWithNibName:@"fengmian" bundle:[NSBundle mainBundle]];
//将当前视图指定为根视图哦
self.window.rootViewController=fengmiancontroller;
}
第四步:myvacationViewController.h
#import <UIKit/UIKit.h>
//引入切换视图接口
#import "SwitchViewDelegate.h"
@interface myvacationViewController : UIViewController {
id<SwitchViewDelegate> delegate;
}
@property(nonatomic,retain) id<SwitchViewDelegate> delegate;
@end
第四步:myvacationViewController.m
#import "myvacationViewController.h"
@implementation myvacationViewController
@synthesize delegate;
在你需要切换到下一个视图的代码里加上如下代码
//将本视图从window移出,如果没有这句,直接加上下一句,本视图还是存在窗体里的,所以你的设备还是无法响应旋转事件
[self.view removeFromSuperview];
//这个是实现getfengmian事件,这个事件用来将下一个视图切换回主视图
[delegate getfengmian];
getfengmian.delegate=self; //这个视图加载后也加入这个deleage,以便它要切换下一个视图到根视图,方便调用