两个视图之前的切换,用Xib文件写了好几次还没很能记的很牢固,所以想用代码在实现一次,也好写写bolg让自己的记的更深点。
先创建一个Empty Applcition的项目后创见3个类,分别为MainViewController、RedViewController、BuleViewController
打开AppDelegate.h添加代码
@property (strong, nonatomic) MainViewController *mainView;
打开AppDelegate.m添加代码
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
self.mainView = [[MainViewController alloc] init];
self.window.rootViewController = self.mainView;
[self.window makeKeyAndVisible];
return YES;
}
初始化父View
mainView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
// View的背景设置为白色
mainView.backgroundColor = [UIColor whiteColor];
初始化最开始显示的红色View
RedViewController *redView = [[RedViewController alloc] init];
self.redViewController = redView;
初始化UIToolBar控件
UIToolbar *myToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
初始化一个UIBarButtonItem并保存到NSMutableArray中,最后Set到myToolbar中
UIToolbar *myToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
NSMutableArray *btnArray = [[NSMutableArray alloc] init];
[btnArray addObject:[[UIBarButtonItem alloc] initWithTitle:@"Switch" style:UIBarButtonItemStyleDone target:self action:@selector(onClickSwitch:)]];
[myToolbar setItems:btnArray];
将刚刚初始化的控件添加到mainView的窗口上
[mainView insertSubview:self.redViewController.view atIndex:0];
[mainView addSubview:myToolbar];
self.view = mainView;
接下来就onClickSwitch的点击事件了
if (self.blueViewController.view.superview == nil)
{
if (self.blueViewController == nil)
{
self.blueViewController = [[[BlueViewController alloc] init] autorelease];
}
[self.redViewController.view removeFromSuperview];
[mainView insertSubview:self.blueViewController.view atIndex:0];
}
else
{
if (self.redViewController == nil)
{
self.redViewController = [[[RedViewController alloc] init] autorelease];
}
[self.blueViewController.view removeFromSuperview];
[mainView insertSubview:self.redViewController.view atIndex:0];
}
2个View切换时的动画效果没有写在Demo里,后面会补充。
DEMO下载
http://pan.baidu.com/share/link?shareid=75535&uk=101519637