有过android开发工作经验的程序猿都知道,andriod的Actvity是其四大组件的核心,负责各种UI的展示。同样IOS也有自己的Actvity只是不叫这个名字而是叫ViewController,再启动的时候,Android只要在manifest中配置lauch的actvity就是首次启动的Actvity,然后所有的页面跳转都是通过stratActvity跳转或者类似的方法,而IOS的ViewController的首次启动的ViewController需要在其delegate中其实就是相当于Android的Application类,delegate中有个方法叫-(BOOL)application: didFinishLaunchWithOptions:
,就是在这个方法里我们启动IOS的启动页ViewControlller,
self.window=[[UIWindow alloc]initwithFrame:[UIScreen mainScreen].bounds];//初始化APP窗口
MainController *main=[[MainController olloc] init];//初始化首次启动的ViewController
UINativeController *rootController=[[UINativeController alloc] initWithRootViewControoler:main];//把首次启动的ViewController转化为UINativieController
/**
之所以要转化为UINativeController是因为他是app的window管理其展示的ViewController的导航器或者说是容器,有UINativeViewController来最终控制展示或者dismiss哪一个ViewController:
比如我们常用的
[self.navigationController pushViewController:newC animated:YES];
//跳转到下一页面
[self.navigationController popViewControllerAnimated:YES];
//返回上一页面
**/
self.window.rootViewController=rootController;//然后付给APP的window的rootViewController正好去展示
//在这里可以设置一下APP的主题比如 stutusbar等的属性
[self.window makekeyAndVisible];//展示
return YES;
再启动之前也可以设置一下,整个APP的整体属性就相当于Android的Theme一样。
下面以FirstViewController(FVC)的按钮button点击后跳转到SecondViewController(SVC)为例说明:
方式一:Storyboard的segues方式
鼠标点击按钮button然后按住control键拖拽到SVC页面,在弹出的segue页面中选择跳转模式即可
优点:操作方便,无代码生成,在storyboard中展示逻辑清晰
缺点:页面较多时不方便查看,团队合作时可维护性差, 多人合作时不建议使用这种方式。
方式二:选项卡UITabBarController控制器
通过调用UITabBarController的addChildViewController方法添加子控制器,代码实例如下:
1
2
3
4
5
6
7
8
9
10
|
UITabBarController *tabbarVC = [[ UITabBarController alloc ] init ];
FirstViewController *FVC = [[FirstViewController ] init ];
FVC.tabBarItem.title = @
"控制器1"
;
FVC.tabBarItem.image = [ UIImage imageNamed : @
"first.png"
];
SecondViewController *SVC = [[SecondViewController ] init ];
SVC.tabBarItem.title = @
"控制器2"
;
SVC. tabBarItem.image = [UIImage imageNamed : @
"new.png"
];
// 添加子控制器(这些子控制器会自动添加到UITabBarController的 viewControllers 数组中)
[tabbarVC addChildViewController :FVC];
[tabbarVC addChildViewController :SVC];
|
优点:代码量较少
缺点:tabbar的ios原生样式不太好看,(不常用,目前不建议使用),如果要使用,建议自定义tabbar
方式三:导航控制器UINavigationController
在FVC的button的监听方法中调用:
1
|
[self.navigationController pushViewController:newC animated:YES];
//跳转到下一页面
|
在SVC的方法中调用:
1
|
[self.navigationController popViewControllerAnimated:YES];
//返回上一页面
|
当有多次跳转发生并希望返回根控制器时,调用:
1
|
[ self .navigationController popToRootViewControllerAnimated: YES ];
//返回根控制器,即最开始的页面
|
方式四:利用 Modal 形式展示控制器
在FVC中调用:
1
|
[ self presentViewController:SVC animated: YES completion:nil];
|
在SVC中调用:
1
|
[ self dismissViewControllerAnimated: YES completion: nil ];
|
方式五:直接更改 UIWindow 的 rootViewController
总结:
Storyboard方式适合个人开发小程序时使用,有团队合作或者项目较大时不建议使用
UITabBarController因为目前系统的原生样式不太美观,不建议使用
推荐使用UINavigationController和Modal,无明显缺点,而且目前大部分程序都使用这两种方式,只是看是否需要导航控制器而确定使用哪种方案