zoukankan      html  css  js  c++  java
  • ios学习-delegate、传值、跳转页面

     

    ios学习-delegate、传值、跳转页面

     
     

    1.打开xcode,然后选择ios--Application--Empty Application一个空项目。

    项目目录:

    2.输入项目名称以及选择保存路径即可。

    3.创建文件夹Model、Controller。

    4.Model文件夹创建User类:User.h User.m

    代码:

    User.h:

    1. #import <Foundation/Foundation.h>  
    2.   
    3. @interface User : NSObject  
    4. @property  (nonatomic, retain) NSString *name;  
    5. @property  (nonatomic, retain) NSString *pword;  
    6. @end  


    User.m:

    1. #import "User.h"  
    2.   
    3. @implementation User  
    4. @synthesize name;  
    5. @synthesize pword;  
    6. @end  

    5.创建controller文件里的4个文件。

    TLViewController.h:

    1. #import <UIKit/UIKit.h>  
    2. #import "UserDelegate.h"  
    3. @interface TLViewController : UIViewController<UserDelegate>  
    4.   
    5. @end  


    UserDelegate协议类在后面。

    TLViewController.m:

    1. #import "TLViewController.h"  
    2. #import "User.h"  
    3. #import "AddViewController.h"  
    4. @interface TLViewController ()  
    5.   
    6. @end  
    7.   
    8. @implementation TLViewController{  
    9.     UILabel *labelname ;  
    10.     UILabel *labelpwd ;  
    11.     User *user;  
    12. }  
    13.   
    14.   
    15. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
    16. {  
    17.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
    18.     if (self) {  
    19.             }  
    20.     return self;  
    21. }  
    22.   
    23. - (void)viewDidLoad  
    24. {  
    25.       
    26.     //显示用户名  
    27.     labelname = [[UILabel alloc]initWithFrame:CGRectMake(50, 20, 200, 50)];  
    28.     //设置显示文字  
    29.       
    30.     labelname.text =[NSString stringWithFormat:@"用户名:%@",user.name];  
    31.     //设置字体:粗体,正常的是 SystemFontOfSize  
    32.     labelname.font = [UIFont boldSystemFontOfSize:20];  
    33.     //设置文字颜色  
    34.     labelname.textColor = [UIColor blackColor];  
    35.     [self.view addSubview:labelname];  
    36.     [labelname release];  
    37.       
    38.       
    39.     //显示密码  
    40.     labelpwd = [[UILabel alloc]initWithFrame:CGRectMake(50, 70., 200, 50)];  
    41.     //设置显示文字  
    42.     labelpwd.text = [NSString stringWithFormat:@"密   码:%@",user.pword];  
    43.     //设置字体:粗体,正常的是 SystemFontOfSize  
    44.     labelpwd.font = [UIFont boldSystemFontOfSize:20];  
    45.     //设置文字颜色  
    46.     labelpwd.textColor = [UIColor blackColor];  
    47.     [self.view addSubview:labelpwd];  
    48.     [labelpwd release];  
    49.       
    50.       
    51.     UIButton *btnAdd=[[UIButton alloc] initWithFrame:CGRectMake(10, 130, 300, 30)];  
    52.     [btnAdd setTitle:@"返    回" forState:UIControlStateNormal];  
    53.     [btnAdd setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];  
    54.     
    55.     [btnAdd.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];  
    56.     btnAdd.backgroundColor = [UIColor redColor];  
    57.     [btnAdd addTarget:self action:@selector(BackView) forControlEvents :UIControlEventTouchUpInside];  
    58.     [self.view addSubview:btnAdd];  
    59.     [btnAdd release];  
    60.   
    61.       
    62.     [super viewDidLoad];  
    63.   
    64.       
    65. }  
    66. -(void)BackView{  
    67. //    AddViewController *ad=[[AddViewController alloc] init];  
    68.       
    69.     [self dismissViewControllerAnimated:YES completion:nil];  
    70. //    [ad release];  
    71. }  
    72.   
    73. -(void)setValue:(User *)userValue{  
    74.     user=userValue;  
    75. }  
    76.   
    77. - (void)didReceiveMemoryWarning  
    78. {  
    79.     [super didReceiveMemoryWarning];  
    80.     // Dispose of any resources that can be recreated.  
    81. }  
    82.   
    83.   
    84.   
    85. @end  


    AddViewController.h:

    1. #import <UIKit/UIKit.h>  
    2. #import "UserDelegate.h"  
    3. @interface AddViewController : UIViewController<UITextFieldDelegate>{  
    4.     id<UserDelegate> deleage;  
    5. }  
    6. @property(assign,nonatomic)id<UserDelegate> delegate;  
    7.   
    8.   
    9.   
    10. @end  


    AddViewController.m:

    1. #import "AddViewController.h"  
    2. #import "User.h"  
    3. #import "TLViewController.h"  
    4.   
    5. @interface AddViewController ()  
    6. {  
    7.     UITextField *tfname;  
    8.     UITextField *tfpassword;  
    9. }  
    10. @end  
    11.   
    12. @implementation AddViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
    13. {  
    14.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
    15.     if (self) {  
    16.         // 下一个界面的返回按钮  
    17.         UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];  
    18.         temporaryBarButtonItem.title = @"返回";  
    19.           
    20.         self.navigationItem.backBarButtonItem = temporaryBarButtonItem;  
    21.         [temporaryBarButtonItem release];  
    22.   
    23.     }  
    24.     return self;  
    25. }  
    26. @synthesize delegate;  
    27. - (void)viewDidLoad  
    28. {  
    29.     [super viewDidLoad];  
    30.       
    31.     UILabel *lname = [[UILabel alloc]initWithFrame:CGRectMake(10, 40, 100, 30)];  
    32.     //设置显示文字  
    33.     lname.text = @"用户名:";  
    34.     //设置字体:粗体,正常的是 SystemFontOfSize  
    35.     lname.font = [UIFont boldSystemFontOfSize:20];  
    36.     //设置文字颜色  
    37.     lname.textColor = [UIColor blackColor];  
    38.     lname.textAlignment=NSTextAlignmentRight;  
    39.     [self.view addSubview:lname];  
    40.     [lname release];  
    41.       
    42.     UILabel *lpassword = [[UILabel alloc]initWithFrame:CGRectMake(10, 80, 100, 30)];  
    43.     //设置显示文字  
    44.     lpassword.text = @"密   码:";  
    45.     //设置字体:粗体,正常的是 SystemFontOfSize  
    46.     lpassword.font = [UIFont boldSystemFontOfSize:20];  
    47.     //设置文字颜色  
    48.     lpassword.textColor = [UIColor blackColor];  
    49.     lpassword.textAlignment=NSTextAlignmentRight;  
    50.     [self.view addSubview:lpassword];  
    51.     [lpassword release];  
    52.       
    53.     tfname= [[UITextField alloc] initWithFrame:CGRectMake(110, 40, 200, 30)];  
    54.     [tfname setBorderStyle:UITextBorderStyleRoundedRect]; //外框类型  
    55.     tfname.placeholder = @"请输入用户名"; //默认显示的字  
    56.     tfname.delegate = self;  
    57.     [self.view addSubview:tfname];  
    58.     [tfname release];  
    59.       
    60.     tfpassword= [[UITextField alloc] initWithFrame:CGRectMake(110, 80, 200, 30)];  
    61.     [tfpassword setBorderStyle:UITextBorderStyleRoundedRect]; //外框类型  
    62.     tfpassword.placeholder = @"请输入密码"; //默认显示的字  
    63.     tfpassword.delegate = self;  
    64.     tfpassword.secureTextEntry = YES; //密码  
    65.     [self.view addSubview:tfpassword];  
    66.     [tfpassword release];  
    67.       
    68.     UIButton *btnAdd=[[UIButton alloc] initWithFrame:CGRectMake(10, 130, 300, 30)];  
    69.     [btnAdd setTitle:@"登       陆" forState:UIControlStateNormal];  
    70.     [btnAdd setTitle:@"登陆中......" forState:UIControlStateHighlighted];  
    71.       
    72.     [btnAdd setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];  
    73.     [btnAdd setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];  
    74.     [btnAdd.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];  
    75.     btnAdd.backgroundColor = [UIColor redColor];  
    76.     [btnAdd addTarget:self action:@selector(LoginUser) forControlEvents :UIControlEventTouchUpInside];  
    77.     [self.view addSubview:btnAdd];  
    78.     [btnAdd release];  
    79.       
    80.     // 创建自定义的触摸手势来实现对键盘的隐藏  
    81.     UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];  
    82.     tapGr.cancelsTouchesInView = NO;  
    83.     [self.view addGestureRecognizer:tapGr];  
    84.   
    85. }  
    86.   
    87. //键盘的隐藏  
    88. -(void)viewTapped:(UITapGestureRecognizer*)tapGr{  
    89.     [tfname resignFirstResponder];  
    90.     [tfpassword resignFirstResponder];  
    91. }  
    92.   
    93.   
    94. //登陆并跳转  
    95. -(void)LoginUser{  
    96.     NSLog(@"%@",tfname.text);  
    97.     TLViewController *tv=[[TLViewController alloc] init];  
    98.     self.delegate=tv;  
    99.     User *user=[[User alloc] init];  
    100.     user.name=tfname.text;  
    101.     user.pword=tfpassword.text;  
    102.     [self.delegate setValue:user];  
    103.     tv.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;  
    104.     [self presentModalViewController:tv  animated:YES];  
    105.     [user release];  
    106.     [tv release];  
    107.       
    108. }  
    109. - (BOOL)textFieldShouldReturn:(UITextField *)textField  
    110. {  
    111.     [textField resignFirstResponder];  
    112.     return YES;  
    113. }  
    114.   
    115. - (void)didReceiveMemoryWarning  
    116. {  
    117.     [super didReceiveMemoryWarning];  
    118.     // Dispose of any resources that can be recreated.  
    119. }  
    120.   
    121. @end  


     

    6.创建UserDelegate类:

    UserDelegate.h:

    1. #import <Foundation/Foundation.h>  
    2. #import "User.h"  
    3.   
    4. @protocol UserDelegate <NSObject>  
    5. -(void)setValue:(User *)userValue;  
    6. @end  


     

    7.AppDelegate文件:

    AppDelegate.h

    1. #import <UIKit/UIKit.h>  
    2. @class TLViewController;  
    3. @class AddViewController;  
    4.   
    5. @interface AppDelegate : UIResponder <UIApplicationDelegate>  
    6.   
    7. @property (strong, nonatomic) UIWindow *window;  
    8.   
    9. @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;  
    10. @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;  
    11. @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;  
    12. //自定义控件  
    13. //@property (strong, nonatomic) TLViewController *viewController;  
    14. @property (strong, nonatomic) AddViewController *addviewController;  
    15.   
    16. - (void)saveContext;  
    17. - (NSURL *)applicationDocumentsDirectory;  
    18.   
    19. @end  


    AppDelegate.m:

    1. #import "AppDelegate.h"  
    2. #import "TLViewController.h"  
    3. #import "AddViewController.h"  
    4. @implementation AppDelegate  
    5.   
    6. @synthesize managedObjectContext = _managedObjectContext;  
    7. @synthesize managedObjectModel = _managedObjectModel;  
    8. @synthesize persistentStoreCoordinator = _persistentStoreCoordinator;  
    9.   
    10. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
    11. {  
    12.     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];  
    13.     // Override point for customization after application launch.  
    14.     self.window.backgroundColor = [UIColor whiteColor];  
    15.     self.addviewController = [[AddViewController alloc] init];  
    16.     self.window.rootViewController = self.addviewController;  
    17.       
    18.     [self.window makeKeyAndVisible];  
    19.     return YES;  
    20. }  
    21.   
    22. - (void)applicationWillResignActive:(UIApplication *)application  
    23. {  
    24.     // 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.  
    25.     // 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.  
    26. }  
    27.   
    28. - (void)applicationDidEnterBackground:(UIApplication *)application  
    29. {  
    30.     // 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.   
    31.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.  
    32. }  
    33.   
    34. - (void)applicationWillEnterForeground:(UIApplication *)application  
    35. {  
    36.     // 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.  
    37. }  
    38.   
    39. - (void)applicationDidBecomeActive:(UIApplication *)application  
    40. {  
    41.     // 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.  
    42. }  
    43.   
    44. - (void)applicationWillTerminate:(UIApplication *)application  
    45. {  
    46.     // Saves changes in the application's managed object context before the application terminates.  
    47.     [self saveContext];  
    48. }  
    49.   
    50. - (void)saveContext  
    51. {  
    52.     NSError *error = nil;  
    53.     NSManagedObjectContext *managedObjectContext = self.managedObjectContext;  
    54.     if (managedObjectContext != nil) {  
    55.         if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {  
    56.              // Replace this implementation with code to handle the error appropriately.  
    57.              // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.   
    58.             NSLog(@"Unresolved error %@, %@", error, [error userInfo]);  
    59.             abort();  
    60.         }   
    61.     }  
    62. }  
    63.   
    64. #pragma mark - Core Data stack  
    65.   
    66. // Returns the managed object context for the application.  
    67. // If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.  
    68. - (NSManagedObjectContext *)managedObjectContext  
    69. {  
    70.     if (_managedObjectContext != nil) {  
    71.         return _managedObjectContext;  
    72.     }  
    73.       
    74.     NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];  
    75.     if (coordinator != nil) {  
    76.         _managedObjectContext = [[NSManagedObjectContext alloc] init];  
    77.         [_managedObjectContext setPersistentStoreCoordinator:coordinator];  
    78.     }  
    79.     return _managedObjectContext;  
    80. }  
    81.   
    82. // Returns the managed object model for the application.  
    83. // If the model doesn't already exist, it is created from the application's model.  
    84. - (NSManagedObjectModel *)managedObjectModel  
    85. {  
    86.     if (_managedObjectModel != nil) {  
    87.         return _managedObjectModel;  
    88.     }  
    89.     NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Login" withExtension:@"momd"];  
    90.     _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];  
    91.     return _managedObjectModel;  
    92. }  
    93.   
    94. // Returns the persistent store coordinator for the application.  
    95. // If the coordinator doesn't already exist, it is created and the application's store added to it.  
    96. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator  
    97. {  
    98.     if (_persistentStoreCoordinator != nil) {  
    99.         return _persistentStoreCoordinator;  
    100.     }  
    101.       
    102.     NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Login.sqlite"];  
    103.       
    104.     NSError *error = nil;  
    105.     _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];  
    106.     if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {  
    107.         /*  
    108.          Replace this implementation with code to handle the error appropriately.  
    109.            
    110.          abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.   
    111.            
    112.          Typical reasons for an error here include:  
    113.          * The persistent store is not accessible;  
    114.          * The schema for the persistent store is incompatible with current managed object model.  
    115.          Check the error message to determine what the actual problem was.  
    116.            
    117.            
    118.          If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.  
    119.            
    120.          If you encounter schema incompatibility errors during development, you can reduce their frequency by:  
    121.          * Simply deleting the existing store:  
    122.          [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]  
    123.            
    124.          * Performing automatic lightweight migration by passing the following dictionary as the options parameter:  
    125.          @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}  
    126.            
    127.          Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.  
    128.            
    129.          */  
    130.         NSLog(@"Unresolved error %@, %@", error, [error userInfo]);  
    131.         abort();  
    132.     }      
    133.       
    134.     return _persistentStoreCoordinator;  
    135. }  
    136.   
    137. #pragma mark - Application's Documents directory  
    138.   
    139. // Returns the URL to the application's Documents directory.  
    140. - (NSURL *)applicationDocumentsDirectory  
    141. {  
    142.     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];  
    143. }  
    144.   
    145. @end  


    效果图:

    本项目传值用到delegate委托,可以可以用更加单的方法传值,就是在B页面定义一个User类,在A页面初始化B时进行赋值:如b.user=user1;

    点击空白区域隐藏键盘,基本都是简单的一个demo而已,仅供参考学习。

    项目如果报:release不能使用。

    ARC forbids explicit message send of'release'

    'release' is unavailable: not available inautomatic reference counting mode

     

    解决办法:

    打开当前工程,打开"Build Settings",找到Objective-C Automatic Reference Counting项,将它的值设置为NO。

  • 相关阅读:
    【前端知识体系-JS相关】组件化和React
    【前端知识体系-JS相关】虚拟DOM和Diff算法
    【前端知识体系-JS相关】ES6专题系列总结
    【前端开发环境】前端使用GIT管理代码仓库需要掌握的几个必备技巧和知识点总结
    webpack代码分离CommonsChunkPlugin插件的使用(防止重复)
    webpack管理输出
    webpack管理资源(loader操作)
    window启动webpack打包的三种方法
    echarts地图map城市间如何连线
    echarts水球图编写
  • 原文地址:https://www.cnblogs.com/iOS-mt/p/4154037.html
Copyright © 2011-2022 走看看