Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 322|回复: 0

[默认分类] iOS开发系列--视图切换

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-7-11 15:13:47 | 显示全部楼层 |阅读模式
    概述
    在iOS开发中视图的切换是很频繁的,独立的视图应用在实际开发过程中并不常见,除非你的应用足够简单。在iOS开发中常用的视图切换有三种,今天我们将一一介绍:

    UITabBarController
    UINavigationController
    模态窗口

    UITabBarController
    iOS三种视图切换的原理各不相同:

    UITabBarController:以平行的方式管理视图,各个视图之间往往关系并不大,每个加入到UITabBarController的视图都会进行初始化即使当前不显示在界面上,相对比较占用内存。
    UINavigationController:以栈的方式管理视图,各个视图的切换就是压栈和出栈操作,出栈后的视图会立即销毁。
    UIModalController:以模态窗口的形式管理视图,当前视图关闭前其他视图上的内容无法操作。

    UITabBarController是Apple专门为了利用页签切换视图而设计的,在这个视图控制器中有一个UITabBar控件,用户通过点击tabBar进行视图切换。我们知道在UIViewController内部有一个视图,一旦创建了UIViewController之后默认就会显示这个视图,但是UITabBarController本身并不会显示任何视图,如果要显示视图则必须设置其viewControllers属性(它默认显示viewControllers[0])。这个属性是一个数组,它维护了所有UITabBarController的子视图。为了尽可能减少视图之间的耦合,所有的UITabBarController的子视图的相关标题、图标等信息均由子视图自己控制,UITabBarController仅仅作为一个容器存在。
      
    假设现在有一个KCTabBarViewController(继承于UITabBarController),它内部有一个KCWebChatViewController、一个KCContactViewController。
    1.首先创建一个KCTabBarViewController继承于UITabBarController(代码是默认生成的,不再贴出来)。
    2.其次创建两个子视图,在这两个子视图控制器中设置对应的名称、图标等信息。
    KCWebChatViewController.m
    1. //
    2. //  KCWorldClockViewController.m
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import "KCWebChatViewController.h"
    9. @interface KCWebChatViewController ()
    10. @end
    11. @implementation KCWebChatViewController
    12. - (void)viewDidLoad {
    13.     [super viewDidLoad];
    14.    
    15.     self.view.backgroundColor=[UIColor redColor];
    16.    
    17.     //设置视图控制器标题
    18.     self.title=@"Chat";
    19.    
    20.     //注意通过tabBarController或者parentViewController可以得到其俯视图控制器(也就是KCTabBarViewController)
    21.     NSLog(@"%i",self.tabBarController==self.parentViewController);//对于当前应用二者相等
    22.    
    23.     //设置图标、标题(tabBarItem是显示在tabBar上的标签)
    24.     self.tabBarItem.title=@"Web Chat";//注意如果这个标题不设置默认在页签上显示视图控制器标题
    25.     self.tabBarItem.image=[UIImage imageNamed:@"tabbar_mainframe.png"];//默认图片
    26.     self.tabBarItem.selectedImage=[UIImage imageNamed:@"tabbar_mainframeHL.png"];//选中图片
    27.    
    28.     //图标右上角内容
    29.     self.tabBarItem.badgeValue=@"5";
    30.    
    31. }
    32. @end
    复制代码
    KCContactViewController.m
    1. //
    2. //  KCAlarmViewController.m
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import "KCContactViewController.h"
    9. @interface KCContactViewController ()
    10. @end
    11. @implementation KCContactViewController
    12. - (void)viewDidLoad {
    13.     [super viewDidLoad];
    14.     self.view.backgroundColor=[UIColor yellowColor];
    15.     self.tabBarItem.title=@"Contact";
    16.     self.tabBarItem.image=[UIImage imageNamed:@"tabbar_contacts.png"];
    17.     self.tabBarItem.selectedImage=[UIImage imageNamed:@"tabbar_contactsHL.png"];
    18. }
    19. @end
    复制代码
    3.在应用程序启动后设置Tab bar视图控制器的子视图,同时将Tab bar视图控制器作为window的根控制器。
    AppDelegate.m
    1. //
    2. //  AppDelegate.m
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import "AppDelegate.h"
    9. #import "KCTabBarViewController.h"
    10. #import "KCWebChatViewController.h"
    11. #import "KCContactViewController.h"
    12. @interface AppDelegate ()
    13. @end
    14. @implementation AppDelegate
    15.             
    16. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    17.    
    18.     _window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    19.    
    20.     KCTabBarViewController *tabBarController=[[KCTabBarViewController alloc]init];
    21.    
    22.     KCWebChatViewController *webChatController=[[KCWebChatViewController alloc]init];
    23.     KCContactViewController *contactController=[[KCContactViewController alloc]init];
    24.     tabBarController.viewControllers=@[webChatController,contactController];
    25.     //注意默认情况下UITabBarController在加载子视图时是懒加载的,所以这里调用一次contactController,否则在第一次展示时只有第一个控制器tab图标,contactController的tab图标不会显示
    26.     for (UIViewController *controller in tabBarController.viewControllers) {
    27.         UIViewController *view= controller.view;
    28.     }
    29.    
    30.     _window.rootViewController=tabBarController;
    31.     [_window makeKeyAndVisible];
    32.    
    33.     return YES;
    34. }
    35. - (void)applicationWillResignActive:(UIApplication *)application {
    36.     // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    37.     // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    38. }
    39. - (void)applicationDidEnterBackground:(UIApplication *)application {
    40.     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    41.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    42. }
    43. - (void)applicationWillEnterForeground:(UIApplication *)application {
    44.     // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    45. }
    46. - (void)applicationDidBecomeActive:(UIApplication *)application {
    47.     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    48. }
    49. - (void)applicationWillTerminate:(UIApplication *)application {
    50.     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    51. }
    52. @end
    复制代码
    运行效果:
          
    对于UITabBarController简单总结如下:

    UITabBarController会一次性初始化所有子控制器,但是默认只加载第一个控制器视图,其他视图控制器只初始化默认不会加载,为了能够将其他子控制器也正常显示在Tab bar中我们访问了每个子视图控制器的视图以便调用其视图加载方法(viewDidLoad);当然,既然会调用子视图的初始化方法,当然也可以将视图控制器的tabBarItem属性设置放到init方法中设置,如此则不用再遍历其视图属性了。
    每个视图控制器都有一个tabBarController属性,通过它可以访问所在的UITabBarController,而且对于UITabBarController的直接子视图其tabBarController等于parentViewController。
    每个视图控制器都有一个tabBarItem属性,通过它控制视图在UITabBarController的tabBar中的显示信息。
    tabBarItem的image属性必须是png格式(建议大小32*32)并且打开alpha通道否则无法正常显示。
    注意:使用storyboard创建UITabBarController的内容今天不再着重讲解,内容比较简单,大家可以自己试验。
    UINavigationController
    代码方式创建导航
    UINavigationController是一个导航控制器,它用来组织有层次关系的视图,在UINavigationController中子控制器以栈的形式存储,只有在栈顶的控制器能够显示在界面中,一旦一个子控制器出栈则会被销毁。UINavigationController默认也不会显示任何视图(这个控制器自身的UIView不会显示),它必须有一个根控制器rootViewController,而且这个根控制器不会像其他子控制器一样被销毁。

    下面简单通过几个视图模拟一下微信添加好友的功能,假设有一个导航控制器,它的根控制器为好友列表控制器KCFriendViewController,通过它可以导航到添加QQ联系人视图KCQQContactViewController,在QQ联系人视图又可以导航到公共账号视图KCPublicAccountViewController。
    1.首先在应用代理启动后初始化一个导航控制器并设置其根控制器为KCFriendViewController
    1. //
    2. //  AppDelegate.m
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import "AppDelegate.h"
    9. #import "KCTabBarViewController.h"
    10. #import "KCWebChatViewController.h"
    11. #import "KCContactViewController.h"
    12. #import "KCFriendViewController.h"
    13. #import "KCQQContactViewController.h"
    14. @interface AppDelegate ()
    15. @end
    16. @implementation AppDelegate
    17.             
    18. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    19.    
    20.     _window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    21.    
    22.     _window.backgroundColor =[UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1];
    23.     //设置全局导航条风格和颜色
    24.     [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:23/255.0 green:180/255.0 blue:237/255.0 alpha:1]];
    25.     [[UINavigationBar appearance] setBarStyle:UIBarStyleBlack];
    26.    
    27.     KCFriendViewController *friendController=[[KCFriendViewController alloc]init];
    28.     UINavigationController *navigationController=[[UINavigationController alloc]initWithRootViewController:friendController];
    29.    
    30.     _window.rootViewController=navigationController;
    31.    
    32.     [_window makeKeyAndVisible];
    33.    
    34.     return YES;
    35. }
    36. - (void)applicationWillResignActive:(UIApplication *)application {
    37.     // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    38.     // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    39. }
    40. - (void)applicationDidEnterBackground:(UIApplication *)application {
    41.     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    42.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    43. }
    44. - (void)applicationWillEnterForeground:(UIApplication *)application {
    45.     // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    46. }
    47. - (void)applicationDidBecomeActive:(UIApplication *)application {
    48.     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    49. }
    50. - (void)applicationWillTerminate:(UIApplication *)application {
    51.     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    52. }
    53. @end
    复制代码
    2.在好友列表视图控制器中设置导航栏左右按钮,并且设置点击右侧按钮导航到添加QQ联系人视图
    1. //
    2. //  KCFriendViewController.m
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import "KCFriendViewController.h"
    9. #import "KCQQContactViewController.h"
    10. @interface KCFriendViewController ()
    11. @end
    12. @implementation KCFriendViewController
    13. - (void)viewDidLoad {
    14.     [super viewDidLoad];
    15.    
    16.     //每次出栈都会销毁相应的子控制器
    17.     NSLog(@"childViewControllers:%@",self.navigationController.childViewControllers);
    18.    
    19.     //在子视图中可以通过navigationController属性访问导航控制器,
    20.     //同时对于当前子视图来说其父控制器就是其导航控制器
    21.     NSLog(@"%i",self.navigationController==self.parentViewController);
    22.    
    23.     //在子视图中(或者根视图)有一个navigationItem用于访问其导航信息
    24.     self.navigationItem.title=@"Friends";//或者直接设置控制器title(例如[self setTitle:@"Friends"])
    25.     //设置导航栏左侧按钮
    26.     self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonSystemItemAdd target:nil action:nil];
    27.     //设置导航栏右侧按钮
    28.     self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ff_IconAdd.png"] style:UIBarButtonItemStyleDone target:self action:@selector(addFriends)];
    29. }
    30. -(void)addFriends{
    31.     //通过push导航到另外一个子视图
    32.     KCQQContactViewController *qqContactController=[[KCQQContactViewController alloc]init];
    33.     [self.navigationController pushViewController:qqContactController animated:YES];
    34. }
    35. @end
    复制代码
    3.在QQ联系人视图右侧导航中添加一个导航到公共账号的按钮
    1. //
    2. //  KCQQContactViewController.m
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import "KCQQContactViewController.h"
    9. #import "KCPublicAccountViewController.h"
    10. @interface KCQQContactViewController ()
    11. @end
    12. @implementation KCQQContactViewController
    13. - (void)viewDidLoad {
    14.     [super viewDidLoad];
    15.    
    16.     //每次出栈都会销毁相应的子控制器
    17.     NSLog(@"childViewControllers:%@",self.navigationController.childViewControllers);
    18.    
    19.     [self setTitle:@"QQ Contact"];
    20.     //self.title=@"QQ contact";
    21.     //self.navigationItem.title=@"My QQ";
    22.    
    23.     UIBarButtonItem *back=[[UIBarButtonItem alloc]initWithTitle:@"QQ" style:UIBarButtonItemStyleDone target:nil action:nil];
    24.     self.navigationItem.backBarButtonItem=back;
    25.    
    26.     self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"Public Account" style:UIBarButtonItemStyleDone target:self action:@selector(gotoNextView)];
    27. }
    28. -(void)gotoNextView{
    29.     KCPublicAccountViewController *publicAccountController=[[KCPublicAccountViewController alloc]init];
    30.     [self.navigationController pushViewController:publicAccountController  animated:YES];
    31. }
    32. @end
    复制代码
    4.在公共账号视图中在导航栏右侧设置一个按钮用于直接返回根视图
    1. //
    2. //  KCPublicNumberViewController.m
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import "KCPublicAccountViewController.h"
    9. @interface KCPublicAccountViewController ()
    10. @end
    11. @implementation KCPublicAccountViewController
    12. - (void)viewDidLoad {
    13.     [super viewDidLoad];
    14.    
    15.     //每次出栈都会销毁相应的子控制器
    16.     NSLog(@"childViewControllers:%@",self.navigationController.childViewControllers);
    17.    
    18.     self.title=@"Public Account";
    19.    
    20.     self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"Add Friends" style:UIBarButtonItemStyleDone target:self action:@selector(gotoAddFriends)];
    21.    
    22. }
    23. -(void)gotoAddFriends{
    24.     //直接跳转到根控制器,也可以使用- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated; 方法
    25.     [self.navigationController popToRootViewControllerAnimated:YES];
    26. }
    27. @end
    复制代码

    UINavigationController默认显示一个根控制器,这个根视图必须指定(前面我们说过UINavigationController和UITabBarController类似仅仅作为导航容器,本身并不会显示视图),通过根控制器导航到其他下一级子视图。
    在子视图中可以通过navigationController访问导航控制器,同时可以通过navigationController的childViewControllers获得当前栈中所有的子视图(注意每一个出栈的子视图都会被销毁)。
    UINavigationController导航是通过上方导航栏进行的(类似的UITabBarController是通过下方UITabBar进行导航),每个放到UINavigationController栈中的子视图都会显示一个导航栏,可以通过子控制器(包括根控制器)的navigationItem访问这个导航栏,修改其左右两边的按钮内容。
    默认情况下除了根控制器之外的其他子控制器左侧都会在导航栏左侧显示返回按钮,点击可以返回上一级视图,同时按钮标题默认为上一级视图的标题,可以通过backBarButtonItem修改。下一级子视图左侧返回按钮上的标题的显示优先级为: 导航栏返回按钮backBarButtonItem的标题(注意不能直接给backBarButtonItem的标题赋值,只能重新给backBarButtonItem赋值)、导航栏navigationItem的标题,视图控制器标题。

    演示效果:

    使用storyboard进行导航
    鉴于很多初学者在学习UINavigationController时看到的多数是使用storyboard方式创建导航,而且storyboard中的segue很多初学者不是很了解,这里简单对storyboard方式创建导航进行介绍。
    下面简单做一个类似于iOS系统设置的导航程序,系统默认进入Settings视图控制器,在Settings界面点击General进行General视图,点击Sounds进入Sounds视图,就那么简单。
    1.首先在Main.storyboard中拖拽一个UINavigationController将应用启动箭头拖拽到新建的UINavigationController中将其作为默认启动视图,在拖拽过程中会发现UINavigationController默认会带一个UITableViewController作为其根控制器。
    2.设置UITableViewController的标题为“Settings”,同时设置UITableView为静态表格并且包含两行,分别在两个UITableViewCell中放置一个UILabel命名为”General”和“Sounds”。
    3.新建两个UITableViewController,标题分别设置为“General”、“Sounds”,按住Ctrl拖拽“Settings”的第一个UITableViewCell到视图控制器“General”,同时选择segue为“push”,拖拽第二个UITableViewCell到视图控制器“Sounds”,同时选择segue为“push”。
    到这里其实我们已经可以通过Settings视图导航到General和Sounds视图了,但是storyboard是如何处理导航的呢?
    前面我们看到导航的过程是通过一个名为“Segue”连接创建的(前面采用的是push方式),那么这个Segue是如何工作的呢?Segue的工作方式分为以下几个步骤:
    1.创建目标视图控制器(也就是前面的General、Sounds视图控制器)
    2.创建Segue对象
    3.调用源视图对象的prepareForSegue:sender:方法
    4.调用Segue对象的perform方法将目标视图控制器推送到屏幕
    5.释放Segue对象
    要解释上面的过程首先我们定义一个KCSettingsTableViewController控制器,它继承于UITableViewController,然后在storyboard中设置“Settings”视图控制器的class属性为KCSettingsTableViewController。同时设置导航到“General”视图控制器的segue的Identifier为“GeneralSegue”,设置导航到“Sounds”控制器的segue的Identifier为“SoundsSegue”。
    然后修改KCSettingsTableViewController.m添加如下代码:
    1. #pragma mark - 导航
    2. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    3.     //源视图控制器
    4.     UITableViewController *settingController=segue.sourceViewController;
    5.     //目标视图控制器
    6.     UITableViewController *tableViewController=segue.destinationViewController;
    7.     NSLog(@"sourceController:%@,destinationController:%@",settingController.navigationItem.title,tableViewController.navigationItem.title);
    8. }
    复制代码
    此时运行程序导航我们会发现此方法会被调用的同时可以打印源视图控制器和目标视图控制器的信息,这一步对应上面所说的第三个步骤。
    接着在”Settings”视图控制器的导航栏左右两侧分别放一个UIBarButtonItem并添加对应事件代码如下:
    1. - (IBAction)toGeneral:(id)sender {
    2.     [self performSegueWithIdentifier:@"GeneralSegue" sender:self];
    3. }
    4. - (IBAction)toSounds:(id)sender {
    5.     [self performSegueWithIdentifier:@"SoundsSegue" sender:self];
    6. }
    复制代码
    此时运行程序发现,使用两个按钮同样可以导航到对应的视图控制器,这一步对应上面第四个步骤,只是默认情况下是自己执行的,这里我们通过手动调用来演示了这个过程。
    运行效果如下:

    模态窗口
    模态窗口只是视图控制器显示的一种方式(在iOS中并没有专门的模态窗口类),模态窗口不依赖于控制器容器(例如前两种视图切换一个依赖于UITabBarController,另一个依赖于UINavigationController),通常用于显示独立的内容,在模态窗口显示的时其他视图的内容无法进行操作。
    模态窗口使用起来比较容易,一般的视图控制器只要调用- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^)(void))completion NS_AVAILABLE_IOS(5_0);方法那么参数中的视图控制器就会以模态窗口的形式展现,同时调用- (void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^)(void))completion NS_AVAILABLE_IOS(5_0);方法就会关闭模态窗口。
    下面的示例中演示了一个登录操作,点击主界面左上方登录按钮以模态窗口的形式展现登录界面,用户点击登录界面中的登录按钮就会返回到主界面。特别强调一点在下面的示例中导航栏是手动创建的,而不是采用UINavigationController,为了帮助大家熟悉导航栏使用同时也了解了UInavigationController中导航栏的本质。
    1.首先创建一个登录界面,在界面中只有两个输入框和一个登录按钮
    1. //
    2. //  KCLoginViewController.m
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import "KCLoginViewController.h"
    9. @interface KCLoginViewController ()
    10. @end
    11. @implementation KCLoginViewController
    12. - (void)viewDidLoad {
    13.     [super viewDidLoad];
    14.    
    15.     [self addLoginForm];
    16. }
    17. -(void)addLoginForm{
    18.     //用户名
    19.     UILabel *lbUserName=[[UILabel alloc]initWithFrame:CGRectMake(50, 150, 100, 30)];
    20.     lbUserName.text=@"用户名:";
    21.     [self.view addSubview:lbUserName];
    22.    
    23.     UITextField *txtUserName=[[UITextField alloc]initWithFrame:CGRectMake(120, 150, 150, 30)];
    24.     txtUserName.borderStyle=UITextBorderStyleRoundedRect;
    25.     [self.view addSubview:txtUserName];
    26.    
    27.     //密码
    28.     UILabel *lbPassword=[[UILabel alloc]initWithFrame:CGRectMake(50, 200, 100, 30)];
    29.     lbPassword.text=@"密码:";
    30.     [self.view addSubview:lbPassword];
    31.    
    32.     UITextField *txtPassword=[[UITextField alloc]initWithFrame:CGRectMake(120, 200, 150, 30)];
    33.     txtPassword.secureTextEntry=YES;
    34.     txtPassword.borderStyle=UITextBorderStyleRoundedRect;
    35.     [self.view addSubview:txtPassword];
    36.    
    37.     //登录按钮
    38.     UIButton *btnLogin=[UIButton buttonWithType:UIButtonTypeSystem];
    39.     btnLogin.frame=CGRectMake(120, 270, 80, 30);
    40.     [btnLogin setTitle:@"登录" forState:UIControlStateNormal];
    41.     [self.view addSubview:btnLogin];
    42.     [btnLogin addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    43. }
    44. #pragma mark 登录操作
    45. -(void)login{
    46.     [self dismissViewControllerAnimated:YES completion:nil];
    47. }
    48. @end
    复制代码
    2.定义主界面视图控制器KCMainViewController,在左上角放一个登录按钮用于弹出登录界面
    1. //
    2. //  KCMainViewController.m
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import "KCMainViewController.h"
    9. #import "KCLoginViewController.h"
    10. @interface KCMainViewController ()
    11. @end
    12. @implementation KCMainViewController
    13. - (void)viewDidLoad {
    14.     [super viewDidLoad];
    15.    
    16.     [self addNavigationBar];
    17. }
    18. #pragma mark 添加导航栏
    19. -(void)addNavigationBar{
    20.     //创建一个导航栏
    21.     UINavigationBar *navigationBar=[[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 44+20)];
    22.     //navigationBar.tintColor=[UIColor whiteColor];
    23.     [self.view addSubview:navigationBar];
    24.     //创建导航控件内容
    25.     UINavigationItem *navigationItem=[[UINavigationItem alloc]initWithTitle:@"Web Chat"];
    26.    
    27.     //左侧添加登录按钮
    28.     UIBarButtonItem *loginButton=[[UIBarButtonItem alloc]initWithTitle:@"登录" style:UIBarButtonItemStyleDone target:self action:@selector(login)];
    29.    
    30.     navigationItem.leftBarButtonItem=loginButton;
    31.    
    32.     //添加内容到导航栏
    33.     [navigationBar pushNavigationItem:navigationItem animated:NO];
    34. }
    35. #pragma mark 登录操作
    36. -(void)login{
    37.     KCLoginViewController *loginController=[[KCLoginViewController alloc]init];
    38.     //调用此方法显示模态窗口
    39.     [self presentViewController:loginController animated:YES completion:nil];
    40. }
    41. @end
    复制代码
    参数传递
    假设用户名输入“kenshincui”,密码输入“123”就认为登录成功,否则登录失败。同时登录成功之后在主视图控制器中显示用户名并且登录按钮变成“注销”。要实现这个功能主要的问题就是如何把登录后的用户名信息传递到主界面?由此引出一个问题:多视图参数传递。
    在iOS开发中常用的参数传递有以下几种方法:

    采用代理模式
    采用iOS消息机制
    通过NSDefault存储(或者文件、数据库存储等)
    通过AppDelegate定义全局变量(或者使用UIApplication、定义一个单例类等)
    通过控制器属性传递

    今天我们主要采用第一种方式进行数据传递,这在iOS开发中也是最常见的一种多视图传参方式。使用代理方式传递参数的步骤如下:
    1.定义协议,协议中定义好传参时所需要的方法
    2.目标视图控制器定义一个代理对象
    3.源视图控制器实现协议并在初始化目标控制器时指定目标控制器的代理为其自身
    4.需要传参的时候在目标窗口调用代理的协议方法
    具体代码如下:
    KCMainViewController.h
    1. //
    2. //  KCMainViewController.h
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import <UIKit/UIKit.h>
    9. #pragma mark 定义一个协议用于参数传递
    10. @protocol KCMainDelegate
    11. -(void)showUserInfoWithUserName:(NSString *)userName;
    12. @end
    13. @interface KCMainViewController : UIViewController
    14. @end
    复制代码
    KCMainViewController.m
    1. //
    2. //  KCMainViewController.m
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import "KCMainViewController.h"
    9. #import "KCLoginViewController.h"
    10. @interface KCMainViewController ()<KCMainDelegate,UIActionSheetDelegate>{
    11.     UILabel *_loginInfo;
    12.     UIBarButtonItem *_loginButton;
    13.     BOOL _isLogon;
    14. }
    15. @end
    16. @implementation KCMainViewController
    17. - (void)viewDidLoad {
    18.     [super viewDidLoad];
    19.    
    20.     [self addNavigationBar];
    21.    
    22.     [self addLoginInfo];
    23. }
    24. #pragma mark 添加信息显示
    25. -(void)addLoginInfo{
    26.     _loginInfo =[[UILabel alloc]initWithFrame:CGRectMake(0, 100,320 ,30)];
    27.     _loginInfo.textAlignment=NSTextAlignmentCenter;
    28.     [self.view addSubview:_loginInfo];
    29. }
    30. #pragma mark 添加导航栏
    31. -(void)addNavigationBar{
    32.     //创建一个导航栏
    33.     UINavigationBar *navigationBar=[[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 44+20)];
    34.     //navigationBar.tintColor=[UIColor whiteColor];
    35.     [self.view addSubview:navigationBar];
    36.     //创建导航控件内容
    37.     UINavigationItem *navigationItem=[[UINavigationItem alloc]initWithTitle:@"Web Chat"];
    38.    
    39.     //左侧添加登录按钮
    40.     _loginButton=[[UIBarButtonItem alloc]initWithTitle:@"登录" style:UIBarButtonItemStyleDone target:self action:@selector(login)];
    41.    
    42.     navigationItem.leftBarButtonItem=_loginButton;
    43.    
    44.     //添加内容到导航栏
    45.     [navigationBar pushNavigationItem:navigationItem animated:NO];
    46. }
    47. #pragma mark 登录操作
    48. -(void)login{
    49.     if (!_isLogon) {
    50.         KCLoginViewController *loginController=[[KCLoginViewController alloc]init];
    51.         loginController.delegate=self;//设置代理
    52.         //调用此方法显示模态窗口
    53.         [self presentViewController:loginController animated:YES completion:nil];
    54.     }else{
    55.         //如果登录之后则处理注销的情况
    56.         //注意当前视图控制器必须实现UIActionSheet代理才能进行操作
    57.         UIActionSheet *actionSheet=[[UIActionSheet alloc]initWithTitle:@"系统信息" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"注销" otherButtonTitles: nil];
    58.         [actionSheet showInView:self.view];
    59.     }
    60. }
    61. #pragma mark 实现代理方法
    62. -(void)showUserInfoWithUserName:(NSString *)userName{
    63.     _isLogon=YES;
    64.     //显示登录用户的信息
    65.     _loginInfo.text=[NSString stringWithFormat:@"Hello,%@!",userName];
    66.     //登录按钮内容改为“注销”
    67.     _loginButton.title=@"注销";
    68. }
    69. #pragma mark 实现注销方法
    70. -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    71.     if (buttonIndex==0) {//注销按钮
    72.         _isLogon=NO;
    73.         _loginButton.title=@"登录";
    74.         _loginInfo.text=@"";
    75.     }
    76. }
    77. @end
    复制代码
    KCLoginViewController.h
    1. //
    2. //  KCLoginViewController.h
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import <UIKit/UIKit.h>
    9. @protocol KCMainDelegate;
    10. @interface KCLoginViewController : UIViewController
    11. #pragma mark 定义代理
    12. @property (nonatomic,strong) id<KCMainDelegate> delegate;
    13. @end
    复制代码
    KCLoginViewController.m
    1. //
    2. //  KCLoginViewController.m
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import "KCLoginViewController.h"
    9. #import "KCMainViewController.h"
    10. @interface KCLoginViewController (){
    11.     UITextField *_txtUserName;
    12.     UITextField *_txtPassword;
    13. }
    14. @end
    15. @implementation KCLoginViewController
    16. - (void)viewDidLoad {
    17.     [super viewDidLoad];
    18.    
    19.     [self addLoginForm];
    20. }
    21. -(void)addLoginForm{
    22.     //用户名
    23.     UILabel *lbUserName=[[UILabel alloc]initWithFrame:CGRectMake(50, 150, 100, 30)];
    24.     lbUserName.text=@"用户名:";
    25.     [self.view addSubview:lbUserName];
    26.    
    27.     _txtUserName=[[UITextField alloc]initWithFrame:CGRectMake(120, 150, 150, 30)];
    28.     _txtUserName.borderStyle=UITextBorderStyleRoundedRect;
    29.     [self.view addSubview:_txtUserName];
    30.    
    31.     //密码
    32.     UILabel *lbPassword=[[UILabel alloc]initWithFrame:CGRectMake(50, 200, 100, 30)];
    33.     lbPassword.text=@"密码:";
    34.     [self.view addSubview:lbPassword];
    35.    
    36.     _txtPassword=[[UITextField alloc]initWithFrame:CGRectMake(120, 200, 150, 30)];
    37.     _txtPassword.secureTextEntry=YES;
    38.     _txtPassword.borderStyle=UITextBorderStyleRoundedRect;
    39.     [self.view addSubview:_txtPassword];
    40.    
    41.     //登录按钮
    42.     UIButton *btnLogin=[UIButton buttonWithType:UIButtonTypeSystem];
    43.     btnLogin.frame=CGRectMake(70, 270, 80, 30);
    44.     [btnLogin setTitle:@"登录" forState:UIControlStateNormal];
    45.     [self.view addSubview:btnLogin];
    46.     [btnLogin addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    47.    
    48.     //取消登录按钮
    49.     UIButton *btnCancel=[UIButton buttonWithType:UIButtonTypeSystem];
    50.     btnCancel.frame=CGRectMake(170, 270, 80, 30);
    51.     [btnCancel setTitle:@"取消" forState:UIControlStateNormal];
    52.     [self.view addSubview:btnCancel];
    53.     [btnCancel addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    54. }
    55. #pragma mark 登录操作
    56. -(void)login{
    57.     if ([_txtUserName.text isEqualToString:@"kenshincui"] && [_txtPassword.text isEqualToString:@"123"] ) {
    58.         //调用代理方法传参
    59.         [self.delegate showUserInfoWithUserName:_txtUserName.text];
    60.         
    61.         [self dismissViewControllerAnimated:YES completion:nil];
    62.     }
    63.     else{
    64.         //登录失败弹出提示信息
    65.         UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"系统信息" message:@"用户名或密码错误,请重新输入!" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
    66.         [alertView show];
    67.     }
    68.    
    69. }
    70. #pragma mark 点击取消
    71. -(void)cancel{
    72.     [self dismissViewControllerAnimated:YES completion:nil];
    73. }
    74. @end
    复制代码
    在上面的代码中,点击登录可以跳转到登录界面,如果用户名、密码输入正确可以回传参数到主界面中(不正确则给出提示),同时修改主界面按钮显示内容。如果已经登录则点击注销会弹出提示,点击确定注销则会注销登录信息。在代码中我们还用到了UIActionSheet和UIAlert,这两个控件其实也是模态窗口,只是没有铺满全屏,大家以后的开发中会经常用到。
    假设登录之后在主视图控制器右上角点击“我”可以弹出当前用户信息如何实现呢?这个时候我们需要从主视图控制器传递参数到子视图控制器,和前面的传参刚好相反,这个时候我们通常使用上面提到的第五个方法,设置目标视图控制器的属性。
    1.首先修改一下主视图控制器
    1. //
    2. //  KCMainViewController.m
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import "KCMainViewController.h"
    9. #import "KCLoginViewController.h"
    10. #import "KCMeViewController.h"
    11. @interface KCMainViewController ()<KCMainDelegate,UIActionSheetDelegate>{
    12.     UILabel *_loginInfo;
    13.     UIBarButtonItem *_loginButton;
    14.     UIBarButtonItem *_meButton;
    15.     BOOL _isLogon;
    16. }
    17. @end
    18. @implementation KCMainViewController
    19. - (void)viewDidLoad {
    20.     [super viewDidLoad];
    21.    
    22.     [self addNavigationBar];
    23.    
    24.     [self addLoginInfo];
    25. }
    26. #pragma mark 添加信息显示
    27. -(void)addLoginInfo{
    28.     _loginInfo =[[UILabel alloc]initWithFrame:CGRectMake(0, 100,320 ,30)];
    29.     _loginInfo.textAlignment=NSTextAlignmentCenter;
    30.     [self.view addSubview:_loginInfo];
    31. }
    32. #pragma mark 添加导航栏
    33. -(void)addNavigationBar{
    34.     //创建一个导航栏
    35.     UINavigationBar *navigationBar=[[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 44+20)];
    36.     //navigationBar.tintColor=[UIColor whiteColor];
    37.     [self.view addSubview:navigationBar];
    38.     //创建导航控件内容
    39.     UINavigationItem *navigationItem=[[UINavigationItem alloc]initWithTitle:@"Web Chat"];
    40.    
    41.     //左侧添加登录按钮
    42.     _loginButton=[[UIBarButtonItem alloc]initWithTitle:@"登录" style:UIBarButtonItemStyleDone target:self action:@selector(login)];
    43.    
    44.     navigationItem.leftBarButtonItem=_loginButton;
    45.    
    46.     //左侧添加导航
    47.     _meButton=[[UIBarButtonItem alloc]initWithTitle:@"我" style:UIBarButtonItemStyleDone target:self action:@selector(showInfo)];
    48.     _meButton.enabled=NO;
    49.     navigationItem.rightBarButtonItem=_meButton;
    50.    
    51.     //添加内容到导航栏
    52.     [navigationBar pushNavigationItem:navigationItem animated:NO];
    53. }
    54. #pragma mark 登录操作
    55. -(void)login{
    56.     if (!_isLogon) {
    57.         KCLoginViewController *loginController=[[KCLoginViewController alloc]init];
    58.         loginController.delegate=self;//设置代理
    59.         //调用此方法显示模态窗口
    60.         [self presentViewController:loginController animated:YES completion:nil];
    61.     }else{
    62.         //如果登录之后则处理注销的情况
    63.         //注意必须实现对应代理
    64.         UIActionSheet *actionSheet=[[UIActionSheet alloc]initWithTitle:@"系统信息" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"注销" otherButtonTitles: nil];
    65.         [actionSheet showInView:self.view];
    66.     }
    67. }
    68. #pragma mark 点击查看我的信息
    69. -(void)showInfo{
    70.     if (_isLogon) {
    71.         KCMeViewController *meController=[[KCMeViewController alloc]init];
    72.         meController.userInfo=_loginInfo.text;
    73.         [self presentViewController:meController animated:YES completion:nil];
    74.     }
    75. }
    76. #pragma mark 实现代理方法
    77. -(void)showUserInfoWithUserName:(NSString *)userName{
    78.     _isLogon=YES;
    79.     //显示登录用户的信息
    80.     _loginInfo.text=[NSString stringWithFormat:@"Hello,%@!",userName];
    81.     //登录按钮内容改为“注销”
    82.     _loginButton.title=@"注销";
    83.     _meButton.enabled=YES;
    84. }
    85. #pragma mark 实现注销方法
    86. -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    87.     if (buttonIndex==0) {//注销按钮
    88.         _isLogon=NO;
    89.         _loginButton.title=@"登录";
    90.         _loginInfo.text=@"";
    91.         _meButton.enabled=NO;
    92.     }
    93. }
    94. @end
    复制代码
    2.添加展示用户信息的控制器视图
    KCMeViewController.h
    1. //
    2. //  KCMeViewController.h
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import <UIKit/UIKit.h>
    9. @interface KCMeViewController : UIViewController
    10. #pragma mark 需要传递的属性参数(很多时候它是一个数据模型)
    11. @property (nonatomic,copy) NSString *userInfo;
    12. @end
    复制代码
    KCMeViewController.m
    1. //
    2. //  KCMeViewController.m
    3. //  ViewTransition
    4. //
    5. //  Created by Kenshin Cui on 14-3-15.
    6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
    7. //
    8. #import "KCMeViewController.h"
    9. @interface KCMeViewController (){
    10.     UILabel *_lbUserInfo;
    11. }
    12. @end
    13. @implementation KCMeViewController
    14. - (void)viewDidLoad {
    15.     [super viewDidLoad];
    16.    
    17.     //信息显示标签
    18.     _lbUserInfo =[[UILabel alloc]initWithFrame:CGRectMake(0, 100,320 ,30)];
    19.     _lbUserInfo.textAlignment=NSTextAlignmentCenter;
    20.     _lbUserInfo.textColor=[UIColor colorWithRed:23/255.0 green:180/255.0 blue:237/255.0 alpha:1];
    21.     [self.view addSubview:_lbUserInfo];
    22.    
    23.     //关闭按钮
    24.     UIButton *btnClose=[UIButton buttonWithType:UIButtonTypeSystem];
    25.     btnClose.frame=CGRectMake(110, 200, 100, 30);
    26.     [btnClose setTitle:@"关闭" forState:UIControlStateNormal];
    27.     [btnClose addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    28.     [self.view addSubview:btnClose];
    29.    
    30.     //设置传值信息
    31.     _lbUserInfo.text=_userInfo;
    32. }
    33. #pragma mark 关闭
    34. -(void)close{
    35.     [self dismissViewControllerAnimated:YES completion:nil];
    36. }
    37. @end
    复制代码
    前面代码中除了演示了模态窗口的使用还演示了两种多视图参数传递方法,其他方法日后我们再做介绍。最后完整展现一下整个示例程序:


    源代码下载
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-3-28 21:00 , Processed in 0.432319 second(s), 48 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表