An overview of the
View switching is very common in iOS development, and separate view apps are not common in actual development unless your app is simple. There are three commonly used view switches in iOS development, which we will cover today:
1.UITabBarController
2.UINavigationController
3. Modal window
UITabBarController
The principles of iOS view switching are different:
- UITabBarController: Manages views in a parallel manner. The relationship between views is often insignificant. Each view added to UITabBarController is initialized even if it is not currently displayed on the interface.
- UINavigationController: Manages views as stacks. Views are pushed and removed from the stack. Views are destroyed immediately after being removed from the stack.
- UIModalController: Manages views in the form of a modal window. The contents of other views cannot be manipulated until the current view is closed.
UITabBarController is specially designed by Apple to switch views using tabs. In this view controller, there is a UITabBar control. Users can switch views by clicking tabBar. We know that inside UIViewController there’s a view, and once UIViewController is created it’s going to show that view by default, but UITabBarController itself doesn’t show any views, If you want to display the view, you must set its viewControllers property (it defaults to viewControllers[0]). This property is an array that maintains the subviews of all uitabBarControllers. In order to minimize the coupling between views, the title, icon and other information of all UITabBarController’s sub-views are controlled by the sub-views themselves, and UITabBarController exists only as a container.
Suppose you now have a KCTabBarViewController (inherited from UITabBarController) with an internal KCWebChatViewController and a KCContactViewController.
1. First create a KCTabBarViewController inherited from UITabBarController (the code is generated by default and will not be posted).
2. Next, create two subviews and set their names and ICONS in the two subview controllers.
KCWebChatViewController.m // // KCWorldClockViewController.m // ViewTransition // // Created by Kenshin Cui on 14-3-15. / / Copyright (c) 2014 Kenshin Cui. All rights reserved. / / # import "KCWebChatViewController. H" @ interface KCWebChatViewController () @end @implementation KCWebChatViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor=[UIColor redColor]; // Set the view controller title self.title=@"Chat"; // Note that tabBarController or parentViewController can get its top view controller (KCTabBarViewController) NSLog(@"%i",self.tabBarController==self.parentViewController); Self.tabbaritem. title=@"Web Chat"; self.tabbarItem. title=@"Web Chat"; Image =[UIImage imageNamed:@"tabbar_mainframe.png"]; // Note that if this title is not set by default, the view controller title is displayed on the TAB. / / the default image self. TabBarItem. SelectedImage = [UIImage imageNamed: @ "tabbar_mainframeHL. PNG"]. / / picture/ICONS/content of the upper right corner of the self. The selected tabBarItem. BadgeValue = @ "5"; } @end KCContactViewController.m // // KCAlarmViewController.m // ViewTransition // // Created by Kenshin Cui on 14-3-15. / / Copyright (c) 2014 Kenshin Cui. All rights reserved. / / # import "KCContactViewController. H" @ interface KCContactViewController () @end @implementation KCContactViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor=[UIColor yellowColor]; self.tabBarItem.title=@"Contact"; self.tabBarItem.image=[UIImage imageNamed:@"tabbar_contacts.png"]; self.tabBarItem.selectedImage=[UIImage imageNamed:@"tabbar_contactsHL.png"]; } @end 3. After the application starts, set the Tab Bar view controller's child view and use the Tab Bar view controller as the root controller of the window. Appdelegate. m // // Appdelegate. m // ViewTransition // // Created by Kenshin Cui on 14-3-15. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // #import "AppDelegate.h" #import "KCTabBarViewController.h" #import "KCWebChatViewController.h" #import "KCContactViewController.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { _window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds]; KCTabBarViewController *tabBarController=[[KCTabBarViewController alloc]init]; KCWebChatViewController *webChatController=[[KCWebChatViewController alloc]init]; KCContactViewController *contactController=[[KCContactViewController alloc]init]; tabBarController.viewControllers=@[webChatController,contactController]; // Note that by default UITabBarController is lazy when loading its child view, so call contactController once, otherwise only the first controller TAB icon will be displayed for the first time, ContactController TAB icon does not show the for (UIViewController * controller in tabBarController. ViewControllers) {UIViewController *view= controller.view; } _window.rootViewController=tabBarController; [_window makeKeyAndVisible]; return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // 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. // 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. } - (void)applicationDidEnterBackground:(UIApplication *)application { // 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. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // 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. } - (void)applicationDidBecomeActive:(UIApplication *)application { // 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. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } @endCopy the code
Operation effect:
UITabBarController is briefly summarized as follows:
- UITabBarController initializes all child controllers at once, but only loads the first controller view by default, Other view controllers just initialize and don’t load by default, so in order to be able to display the other child controllers properly in Tab bar we access the view of each child view controller to call its view load method (viewDidLoad); Of course, since the initialization method of the subview is called, you can also set the tabBarItem property of the view controller in the init method so that you don’t have to iterate over its view properties.
- Each view controller has a tabBarController property that gives access to its UITabBarController, And for a direct child of UITabBarController, its tabBarController is equal to parentViewController.
- Each view controller has a tabBarItem property that controls the view’s display in the tabBar of the UITabBarController.
- The image property of a tabBarItem must be in PNG format (recommended size 32*32) and the alpha channel is turned on otherwise it will not display properly.
Note: Creating a UITabBarController in storyboard is not going to be a big part of the story today, so you can try it out for yourself.
UINavigationController
Create navigation code
UINavigationController is a navigation controller used to organize hierarchical views. In UINavigationController, the sub-controllers are stored as stacks, and only the controllers at the top of the stack can be displayed in the interface. Once a sub-controller goes off the stack, it is destroyed. UINavigationController also does not display any views by default (the controller’s own UIView does not), it must have a root controller rootViewController, and this root controller is not destroyed like other child controllers.
Simply by following several view simulate WeChat add buddy, let’s assume that we have a navigation controller, its root controller for friends list controller KCFriendViewController, through which you can navigate to the add QQ contact view KCQQContactViewController, In the QQ contact view account view KCPublicAccountViewController can navigate to the public.
1. Initialize a navigation controller and set its root controller to KCFriendViewController after the application agent starts
// // appdelegate. m // ViewTransition // // Created by Kenshin Cui on 14-3-15. // Copyright (c) 2014 Kenshin Cui. All rights reserved. // #import "AppDelegate.h" #import "KCTabBarViewController.h" #import "KCWebChatViewController.h" #import "KCContactViewController.h" #import "KCFriendViewController.h" #import "KCQQContactViewController.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { _window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds]; BackgroundColor =[UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1]; _window.backgroundColor =[UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1]; // Set the global navigation bar style and color [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:23/255.0 green:180/255.0 Alpha blue: 237/255.0:1]]; [[UINavigationBar appearance] setBarStyle:UIBarStyleBlack]; KCFriendViewController *friendController=[[KCFriendViewController alloc]init]; UINavigationController *navigationController=[[UINavigationController alloc]initWithRootViewController:friendController]; _window.rootViewController=navigationController; [_window makeKeyAndVisible]; return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // 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. // 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. } - (void)applicationDidEnterBackground:(UIApplication *)application { // 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. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // 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. } - (void)applicationDidBecomeActive:(UIApplication *)application { // 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. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } @endCopy the code
2. Set the left and right buttons in the navigation bar in the Friends List view controller and click the right button to navigate to the Add QQ Contact view
// // kcfriendViewController. m // ViewTransition // // Created by Kenshin Cui on 14-3-15. // Copyright (c) 2014 Kenshin Cui. All rights reserved. // #import "KCFriendViewController.h" #import "KCQQContactViewController.h" @interface KCFriendViewController () @end @implementation KCFriendViewController - (void)viewDidLoad { [super viewDidLoad]; Son / / every time out of the stack will destroy the corresponding controller NSLog (@ "childViewControllers: % @", the self. The navigationController. ChildViewControllers); // the navigationController can be accessed in the subview via the navigationController property, / / for the current child views his father at the same time controller is its navigation controller NSLog (@ % "I", the self. The navigationController = = self. ParentViewController); / / in the child views (or view) has a navigationItem used to access the navigation information self. The navigationItem. Title = @ "Friends"; / / title or directly set controller (for example [self setTitle: @ "Friends"]) / / set the navigation bar on the left side of the button to the self. The navigationItem. LeftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonSystemItemAdd target:nil action:nil]; / / set the navigation bar on the right side button self. The navigationItem. RightBarButtonItem = [[UIBarButtonItem alloc] initWithImage: [UIImage imageNamed:@"ff_IconAdd.png"] style:UIBarButtonItemStyleDone target:self action:@selector(addFriends)]; } - (void) addFriends {/ / navigate by the push to another child view KCQQContactViewController * qqContactController = [[KCQQContactViewController alloc]init]; [self.navigationController pushViewController:qqContactController animated:YES]; } @ end (3) a is added in the QQ contact view on the right side navigation navigation button to public account / / / / KCQQContactViewController. M / / ViewTransition / / / / Created by Kenshin Cui on 14-3-15. / / Copyright (c) 2014 Kenshin Cui. All rights reserved. / / # import "KCQQContactViewController. H # import" "KCPublicAccountViewController.h" @interface KCQQContactViewController () @end @implementation KCQQContactViewController - (void)viewDidLoad { [super viewDidLoad]; Son / / every time out of the stack will destroy the corresponding controller NSLog (@ "childViewControllers: % @", the self. The navigationController. ChildViewControllers); [self setTitle:@"QQ Contact"]; //self.title=@"QQ contact"; //self.navigationItem.title=@"My QQ"; UIBarButtonItem *back=[[UIBarButtonItem alloc]initWithTitle:@"QQ" style:UIBarButtonItemStyleDone target:nil action:nil]; self.navigationItem.backBarButtonItem=back; self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"Public Account" style:UIBarButtonItemStyleDone target:self action:@selector(gotoNextView)]; } -(void)gotoNextView{ KCPublicAccountViewController *publicAccountController=[[KCPublicAccountViewController alloc]init]; [self.navigationController pushViewController:publicAccountController animated:YES]; 4} @ end in a public account view in the navigation bar on the right side of a button to directly return the root view. / / / / KCPublicNumberViewController m / / ViewTransition / / / / Created by Kenshin Cui on the 14-3-15. / / Copyright (c) 2014 Kenshin Cui. All rights reserved. / / # import "KCPublicAccountViewController. H" @interface KCPublicAccountViewController () @end @implementation KCPublicAccountViewController - (void)viewDidLoad { [super viewDidLoad]; Son / / every time out of the stack will destroy the corresponding controller NSLog (@ "childViewControllers: % @", the self. The navigationController. ChildViewControllers); self.title=@"Public Account"; self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"Add Friends" style:UIBarButtonItemStyleDone target:self action:@selector(gotoAddFriends)]; } -(void)gotoAddFriends{// Go to the root controller, You can also use - (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated; Methods [self navigationController popToRootViewControllerAnimated: YES]; } @endCopy the code
- UINavigationController displays a root controller by default. This root view must be specified. Navigate to other next-level subviews through the root controller.
- NavigationController can access the navigationController in the child view, and navigationController’s childViewControllers can get all the child views in the current stack (note that every child view that goes off the stack is destroyed).
- UINavigationController is navigated through the upper navigation bar (similarly, UITabBarController is navigated through the lower UITabBar), and each child view placed in the UINavigationController stack displays a navigation bar, You can access the navigation bar through the navigationItem of the child controllers, including the root controller, and modify the content of the buttons on the left and right sides.
- By default, the left side of all child controllers except the root controller will display a back button on the left side of the navigation bar. Click to return to the upper view. At the same time, the title of the button defaults to the title of the upper view, which can be changed by backBarButtonItem. The display priority of the title on the back button to the left of the next-level subview is: The navigation bar returns the title of the backBarButtonItem button, the title of the navigation bar’s navigationItem, and the title of the view controller.
Demo effect:
Navigation in a storyboard and since a lot of beginners when they learn about UINavigationController are going to see a lot of navigation in a storyboard, and segues in a storyboard are not very familiar to a lot of beginners, Here’s a quick introduction to creating navigation in storyboard.
So let’s do a little bit of navigation similar to iOS Settings, and by default, the system goes to Settings view controller, and in Settings, click General to get the General view, click “Sounds” to get the “Sounds” view, and that’s it.
1. First drag a UINavigationController from main. storyboard and drag the application startup arrow to the new UINavigationController as the default startup view, As you drag and drop, you’ll notice that the UINavigationController takes a UITableViewController as its root controller by default.
2. Set the title of the UITableViewController to “Settings” and set the UITableView to a static table containing two rows. Place a UILabel in each of the two UITableViewCells named “General” and “Sounds”.
3. Create two new UITableViewControllers, set the titles to “General” and “Sounds” respectively, hold down Ctrl and drag the first UITableViewCell from “Settings” to the view controller “General”. And then segue to push, drag the second UITableViewCell to the view controller Sounds, and segue to push.
So now we can actually navigate to the General and Sounds views using the Settings view, but how does the storyboard handle navigation?
We saw that navigation is created through a “Segue” connection (push), so how does this Segue work? There are several steps to how a Segue works:
1. Create the target view controller (General, Sounds view controller)
2. Create the Segue object
3. Call the prepareForSegue: Sender: method of the source view object
4. Call the Segue object’s Perform method to push the target view controller to the screen
5. Release the Segue object
To explain the above process, first of all, we define a KCSettingsTableViewController controller, it is inherited from UITableViewController, Then set the “Settings” in the storyboard view controller class attribute for the KCSettingsTableViewController. Also set the Identifier of the segue to the “General” view controller to “GeneralSegue” and the Identifier of the segue to the “Sounds” controller to “SoundsSegue”.
And then modify the KCSettingsTableViewController. M to add the following code:
#pragma mark - navigation -(void)prepareForSegue (UIStoryboardSegue *)segue Sender (id) Sender {// Source ViewController UITableViewController *settingController=segue.sourceViewController; / / target view controller UITableViewController. * tableViewController = segue destinationViewController; NSLog(@"sourceController:%@,destinationController:%@",settingController.navigationItem.title,tableViewController.navigat ionItem.title); }Copy the code
When we run the application navigation, we’ll see that this method is called and we can print the source view controller and the destination view controller, which corresponds to step 3 above.
Then place a UIBarButtonItem on the left and right of the navigation bar of the “Settings” view controller and add the corresponding event code as follows:
- (IBAction)toGeneral:(id)sender {
[self performSegueWithIdentifier:@"GeneralSegue" sender:self];
}
- (IBAction)toSounds:(id)sender {
[self performSegueWithIdentifier:@"SoundsSegue" sender:self];
}
Copy the code
This step corresponds to the fourth step above, but is performed by itself by default. We demonstrate this process here by making a manual call.
The running effect is as follows:
Modal Windows are just a way of displaying a view controller (there is no special modal window class in iOS). Modal Windows do not depend on the controller container (for example, the first two view switches rely on UITabBarController and the other on UINavigationController). Typically used to display standalone content that cannot be manipulated in a modal window while the content of other views is displayed.
Modal Windows are easier to use, and a typical view controller simply calls – (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^)(void))completion NS_AVAILABLE_IOS(5_0); Method the view controller parameters will show in the form of the modal window, at the same time call the – (void) dismissViewControllerAnimated: (BOOL) flag completion: (void (^)(void))completion NS_AVAILABLE_IOS(5_0); Method closes the modal window.
The following example demonstrates a login operation. Click the login button in the upper left of the main interface to display the login interface in the form of a modal window. The user clicks the login button in the login interface to return to the main interface. It is important to note that in the following example the navigation bar is created manually, rather than using UINavigationController. To help you get used to the navigation bar and understand the nature of the navigation bar in UINavigationController.
1. Create a login screen with only two input boxes and a login button
// // kcloginViewController. m // ViewTransition // // Created by Kenshin Cui on 14-3-15. // Copyright (c) 2014 Kenshin Cui. All rights reserved. // #import "KCLoginViewController.h" @interface KCLoginViewController () @end @implementation KCLoginViewController - (void)viewDidLoad { [super viewDidLoad]; [self addLoginForm]; } -(void)addLoginForm{// Username UILabel *lbUserName=[[UILabel alloc]initWithFrame:CGRectMake(50, 150, 100, 30)]; // Username UILabel *lbUserName=[[UILabel alloc]initWithFrame:CGRectMake(50, 150, 100, 30)]; Lbusername. text=@" username: "; [self.view addSubview:lbUserName]; UITextField *txtUserName=[[UITextField alloc]initWithFrame:CGRectMake(120, 150, 150, 30)]; txtUserName.borderStyle=UITextBorderStyleRoundedRect; [self.view addSubview:txtUserName]; UILabel *lbPassword=[[UILabel alloc]initWithFrame:CGRectMake(50, 200, 100, 30)]; Lbpassword. text=@" password: "; [self.view addSubview:lbPassword]; UITextField *txtPassword=[[UITextField alloc]initWithFrame:CGRectMake(120, 200, 150, 30)]; txtPassword.secureTextEntry=YES; txtPassword.borderStyle=UITextBorderStyleRoundedRect; [self.view addSubview:txtPassword]; / / login button UIButton * btnLogin = [UIButton buttonWithType: UIButtonTypeSystem]; btnLogin.frame=CGRectMake(120, 270, 80, 30); [btnLogin setTitle: @ "login" forState: UIControlStateNormal]; [self.view addSubview:btnLogin]; [btnLogin addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside]; } # pragma mark the login operation - (void) login {[self dismissViewControllerAnimated: YES completion: nil]; } @endCopy the code
2. Define the main interface view controller KCMainViewController and put a login button in the upper left corner to pop up the login interface
// // kcmainViewController. m // ViewTransition // // Created by Kenshin Cui on 14-3-15. // Copyright (c) 2014 Kenshin Cui. All rights reserved. // #import "KCMainViewController.h" #import "KCLoginViewController.h" @interface KCMainViewController () @end @implementation KCMainViewController - (void)viewDidLoad { [super viewDidLoad]; [self addNavigationBar]; } #pragma mark adds navigationBar -(void)addNavigationBar{// create a navigationBar UINavigationBar *navigationBar=[[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 44+20)]; //navigationBar.tintColor=[UIColor whiteColor]; [self.view addSubview:navigationBar]; UINavigationItem *navigationItem=[[UINavigationItem alloc]initWithTitle:@"Web Chat"]; / / the left to add a login button UIBarButtonItem * loginButton = [[UIBarButtonItem alloc] initWithTitle: @ "login" style: UIBarButtonItemStyleDone target:self action:@selector(login)]; navigationItem.leftBarButtonItem=loginButton; / / add content to a navigation bar [navigationBar pushNavigationItem: navigationItem animated: NO]; } #pragma mark login{KCLoginViewController *loginController=[[KCLoginViewController alloc]init]; / / this method is called according to the modal window [self presentViewController: loginController animated: YES completion: nil]; } @endCopy the code
Parameter passing
If the user name is “Kenshincui” and the password is “123”, the login is considered successful; otherwise, the login fails. After successful login, the user name is displayed in the master view controller and the login button changes to “Log out”. To achieve this function, the main problem is how to transfer the user name information after login to the main interface? This leads to a problem: multi-view parameter passing.
There are several methods of parameter passing commonly used in iOS development:
Using proxy mode using iOS messaging mechanism via NSDefault store (or file, database store, etc.) via AppDelegate defining global variables (or using UIApplication, defining a singleton class, etc.) via controller properties Today we’re going to focus on the first method for data passing, which is the most common multi-view method in iOS development. The steps for passing parameters in proxy mode are as follows:
1. Define a protocol. The protocol defines the methods required for parameter transmission
2. The target view controller defines a proxy object
3. The source view controller implements the protocol and specifies the proxy of the target controller as itself when initializing the target controller
4. Call the protocol method of the proxy in the target window when parameters need to be passed
The specific code is as follows:
KCMainViewController.h
//
// KCMainViewController.h
// ViewTransition
//
// Created by Kenshin Cui on 14-3-15.
// Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//
#import <UIKit/UIKit.h>
#pragma mark 定义一个协议用于参数传递
@protocol KCMainDelegate
-(void)showUserInfoWithUserName:(NSString *)userName;
@end
@interface KCMainViewController : UIViewController
@end
KCMainViewController.m
//
// KCMainViewController.m
// ViewTransition
//
// Created by Kenshin Cui on 14-3-15.
// Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//
#import "KCMainViewController.h"
#import "KCLoginViewController.h"
@interface KCMainViewController ()<KCMainDelegate,UIActionSheetDelegate>{
UILabel *_loginInfo;
UIBarButtonItem *_loginButton;
BOOL _isLogon;
}
@end
@implementation KCMainViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self addNavigationBar];
[self addLoginInfo];
}
#pragma mark 添加信息显示
-(void)addLoginInfo{
_loginInfo =[[UILabel alloc]initWithFrame:CGRectMake(0, 100,320 ,30)];
_loginInfo.textAlignment=NSTextAlignmentCenter;
[self.view addSubview:_loginInfo];
}
#pragma mark 添加导航栏
-(void)addNavigationBar{
//创建一个导航栏
UINavigationBar *navigationBar=[[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 44+20)];
//navigationBar.tintColor=[UIColor whiteColor];
[self.view addSubview:navigationBar];
//创建导航控件内容
UINavigationItem *navigationItem=[[UINavigationItem alloc]initWithTitle:@"Web Chat"];
//左侧添加登录按钮
_loginButton=[[UIBarButtonItem alloc]initWithTitle:@"登录" style:UIBarButtonItemStyleDone target:self action:@selector(login)];
navigationItem.leftBarButtonItem=_loginButton;
//添加内容到导航栏
[navigationBar pushNavigationItem:navigationItem animated:NO];
}
#pragma mark 登录操作
-(void)login{
if (!_isLogon) {
KCLoginViewController *loginController=[[KCLoginViewController alloc]init];
loginController.delegate=self;//设置代理
//调用此方法显示模态窗口
[self presentViewController:loginController animated:YES completion:nil];
}else{
//如果登录之后则处理注销的情况
//注意当前视图控制器必须实现UIActionSheet代理才能进行操作
UIActionSheet *actionSheet=[[UIActionSheet alloc]initWithTitle:@"系统信息" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"注销" otherButtonTitles: nil];
[actionSheet showInView:self.view];
}
}
#pragma mark 实现代理方法
-(void)showUserInfoWithUserName:(NSString *)userName{
_isLogon=YES;
//显示登录用户的信息
_loginInfo.text=[NSString stringWithFormat:@"Hello,%@!",userName];
//登录按钮内容改为“注销”
_loginButton.title=@"注销";
}
#pragma mark 实现注销方法
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex==0) {//注销按钮
_isLogon=NO;
_loginButton.title=@"登录";
_loginInfo.text=@"";
}
}
@end
KCLoginViewController.h
//
// KCLoginViewController.h
// ViewTransition
//
// Created by Kenshin Cui on 14-3-15.
// Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol KCMainDelegate;
@interface KCLoginViewController : UIViewController
#pragma mark 定义代理
@property (nonatomic,strong) id<KCMainDelegate> delegate;
@end
KCLoginViewController.m
//
// KCLoginViewController.m
// ViewTransition
//
// Created by Kenshin Cui on 14-3-15.
// Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//
#import "KCLoginViewController.h"
#import "KCMainViewController.h"
@interface KCLoginViewController (){
UITextField *_txtUserName;
UITextField *_txtPassword;
}
@end
@implementation KCLoginViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self addLoginForm];
}
-(void)addLoginForm{
//用户名
UILabel *lbUserName=[[UILabel alloc]initWithFrame:CGRectMake(50, 150, 100, 30)];
lbUserName.text=@"用户名:";
[self.view addSubview:lbUserName];
_txtUserName=[[UITextField alloc]initWithFrame:CGRectMake(120, 150, 150, 30)];
_txtUserName.borderStyle=UITextBorderStyleRoundedRect;
[self.view addSubview:_txtUserName];
//密码
UILabel *lbPassword=[[UILabel alloc]initWithFrame:CGRectMake(50, 200, 100, 30)];
lbPassword.text=@"密码:";
[self.view addSubview:lbPassword];
_txtPassword=[[UITextField alloc]initWithFrame:CGRectMake(120, 200, 150, 30)];
_txtPassword.secureTextEntry=YES;
_txtPassword.borderStyle=UITextBorderStyleRoundedRect;
[self.view addSubview:_txtPassword];
//登录按钮
UIButton *btnLogin=[UIButton buttonWithType:UIButtonTypeSystem];
btnLogin.frame=CGRectMake(70, 270, 80, 30);
[btnLogin setTitle:@"登录" forState:UIControlStateNormal];
[self.view addSubview:btnLogin];
[btnLogin addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
//取消登录按钮
UIButton *btnCancel=[UIButton buttonWithType:UIButtonTypeSystem];
btnCancel.frame=CGRectMake(170, 270, 80, 30);
[btnCancel setTitle:@"取消" forState:UIControlStateNormal];
[self.view addSubview:btnCancel];
[btnCancel addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark 登录操作
-(void)login{
if ([_txtUserName.text isEqualToString:@"kenshincui"] && [_txtPassword.text isEqualToString:@"123"] ) {
//调用代理方法传参
[self.delegate showUserInfoWithUserName:_txtUserName.text];
[self dismissViewControllerAnimated:YES completion:nil];
}
else{
//登录失败弹出提示信息
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"系统信息" message:@"用户名或密码错误,请重新输入!" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
[alertView show];
}
}
#pragma mark 点击取消
-(void)cancel{
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
Copy the code
In the above code, click Login to jump to the login interface. If the user name and password are correct, the parameters can be sent back to the main interface (if incorrect, it will give a hint), and modify the display content of the button on the main interface. If you have logged in, click Logout and a prompt will pop up. If you click OK to log out, the login information will be logged out. In the code we also use UIActionSheet and UIAlert, which are actually modal Windows, but they don’t cover the whole screen, and you’ll use them a lot in future development.
What if I click “I” in the upper right corner of the main view controller after logging in to pop up the current user information? In this case, we need to pass parameters from the master view controller to the child view controller, as opposed to the previous one, and we usually use the fifth method mentioned above to set the properties of the target view controller.
1. First modify the main view controller
// // kcmainViewController. m // ViewTransition // // Created by Kenshin Cui on 14-3-15. // Copyright (c) 2014 Kenshin Cui. All rights reserved. // #import "KCMainViewController.h" #import "KCLoginViewController.h" #import "KCMeViewController.h" @interface KCMainViewController ()<KCMainDelegate,UIActionSheetDelegate>{ UILabel *_loginInfo; UIBarButtonItem *_loginButton; UIBarButtonItem *_meButton; BOOL _isLogon; } @end @implementation KCMainViewController - (void)viewDidLoad { [super viewDidLoad]; [self addNavigationBar]; [self addLoginInfo]; } #pragma mark adds information to display -(void)addLoginInfo{_loginInfo =[[UILabel alloc]initWithFrame:CGRectMake(0, 100,320,30)]; _loginInfo.textAlignment=NSTextAlignmentCenter; [self.view addSubview:_loginInfo]; } #pragma mark adds navigationBar -(void)addNavigationBar{// create a navigationBar UINavigationBar *navigationBar=[[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 44+20)]; //navigationBar.tintColor=[UIColor whiteColor]; [self.view addSubview:navigationBar]; UINavigationItem *navigationItem=[[UINavigationItem alloc]initWithTitle:@"Web Chat"]; / / the left to add a login button _loginButton = [[UIBarButtonItem alloc] initWithTitle: @ "login" style: UIBarButtonItemStyleDone target: the self action:@selector(login)]; navigationItem.leftBarButtonItem=_loginButton; / / the left navigation _meButton = [[UIBarButtonItem alloc] initWithTitle: @ "I" style: UIBarButtonItemStyleDone target: the self action:@selector(showInfo)]; _meButton.enabled=NO; navigationItem.rightBarButtonItem=_meButton; / / add content to a navigation bar [navigationBar pushNavigationItem: navigationItem animated: NO]; } #pragma mark -(void)login{if (! _isLogon) { KCLoginViewController *loginController=[[KCLoginViewController alloc]init]; loginController.delegate=self; / / set the proxy / / call the method shows that the modal window [self presentViewController: loginController animated: YES completion: nil]; UIActionSheet *actionSheet=[[UIActionSheet alloc]initWithTitle:@" System info" Self cancelButtonTitle:@" Cancel "destructiveButtonTitle:@" cancel" otherButtonTitles: nil]; [actionSheet showInView:self.view]; -(void)showInfo{if (_isLogon) {KCMeViewController *meController=[[KCMeViewController alloc]init]; meController.userInfo=_loginInfo.text; [self presentViewController:meController animated:YES completion:nil]; }} # pragma mark agents implementation method - (void) showUserInfoWithUserName userName: (nsstrings *) {_isLogon = YES; _logininfo. text=[NSString stringWithFormat:@"Hello,%@!",userName]; _loginbutton. title=@" log out "; _meButton.enabled=YES; } #pragma mark implements logout methods -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{if (buttonIndex==0) {// The logout button _isLogon=NO; _loginButton. Title = @ "login"; _loginInfo.text=@""; _meButton.enabled=NO; Kcmeviewcontroller. h // // kcmeViewController. h // ViewTransition // // Created by Kenshin Cui // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // #import <UIKit/ uikit.h > @interface KCMeViewController : UIViewController #pragma mark Is a property parameter that needs to be passed (most of the time it is a data model) @Property (nonatomic,copy) NSString *userInfo; @end KCMeViewController.m // // KCMeViewController.m // ViewTransition // // Created by Kenshin Cui on 14-3-15. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // #import "KCMeViewController (){ UILabel *_lbUserInfo; } @end @implementation KCMeViewController - (void)viewDidLoad { [super viewDidLoad]; _lbUserInfo =[[UILabel alloc]initWithFrame:CGRectMake(0, 100,320,30)]; _lbUserInfo.textAlignment=NSTextAlignmentCenter; TextColor =[UIColor colorWithRed:23/255.0 green:180/255.0 blue:237/255.0 alpha:1]; _lbuserInfo.textcolor =[UIColor colorWithRed:23/255.0 green:180/255.0 blue:237/255.0 alpha:1]; [self.view addSubview:_lbUserInfo]; / / close button UIButton * btnClose = [UIButton buttonWithType: UIButtonTypeSystem]; btnClose.frame=CGRectMake(110, 200, 100, 30); [btnClose setTitle: @ "closed" forState: UIControlStateNormal]; [btnClose addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btnClose]; _lbuserinfo.text =_userInfo; } # pragma mark off - (void) close {[self dismissViewControllerAnimated: YES completion: nil]; } @endCopy the code
In addition to demonstrating the use of modal Windows, the previous code also demonstrates two methods of passing multi-view parameters, which we will cover in the future. Finally, take a look at the entire sample program:
Original author: KenshinCui
The original link: www.cnblogs.com/kenshincui/…