ios学习-delegate、传值、跳转页面
1.打开xcode,然后选择ios--Application--Empty Application一个空项目。
项目目录:
2.输入项目名称以及选择保存路径即可。
3.创建文件夹Model、Controller。
4.Model文件夹创建User类:User.h User.m
代码:
User.h:
- #import <Foundation/Foundation.h>
- @interface User : NSObject
- @property (nonatomic, retain) NSString *name;
- @property (nonatomic, retain) NSString *pword;
- @end
User.m:
- #import "User.h"
- @implementation User
- @synthesize name;
- @synthesize pword;
- @end
5.创建controller文件里的4个文件。
TLViewController.h:
- #import <UIKit/UIKit.h>
- #import "UserDelegate.h"
- @interface TLViewController : UIViewController<UserDelegate>
- @end
UserDelegate协议类在后面。
TLViewController.m:
- #import "TLViewController.h"
- #import "User.h"
- #import "AddViewController.h"
- @interface TLViewController ()
- @end
- @implementation TLViewController{
- UILabel *labelname ;
- UILabel *labelpwd ;
- User *user;
- }
- - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
- {
- self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
- if (self) {
- }
- return self;
- }
- - (void)viewDidLoad
- {
- //显示用户名
- labelname = [[UILabel alloc]initWithFrame:CGRectMake(50, 20, 200, 50)];
- //设置显示文字
- labelname.text =[NSString stringWithFormat:@"用户名:%@",user.name];
- //设置字体:粗体,正常的是 SystemFontOfSize
- labelname.font = [UIFont boldSystemFontOfSize:20];
- //设置文字颜色
- labelname.textColor = [UIColor blackColor];
- [self.view addSubview:labelname];
- [labelname release];
- //显示密码
- labelpwd = [[UILabel alloc]initWithFrame:CGRectMake(50, 70., 200, 50)];
- //设置显示文字
- labelpwd.text = [NSString stringWithFormat:@"密 码:%@",user.pword];
- //设置字体:粗体,正常的是 SystemFontOfSize
- labelpwd.font = [UIFont boldSystemFontOfSize:20];
- //设置文字颜色
- labelpwd.textColor = [UIColor blackColor];
- [self.view addSubview:labelpwd];
- [labelpwd release];
- UIButton *btnAdd=[[UIButton alloc] initWithFrame:CGRectMake(10, 130, 300, 30)];
- [btnAdd setTitle:@"返 回" forState:UIControlStateNormal];
- [btnAdd setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
- [btnAdd.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
- btnAdd.backgroundColor = [UIColor redColor];
- [btnAdd addTarget:self action:@selector(BackView) forControlEvents :UIControlEventTouchUpInside];
- [self.view addSubview:btnAdd];
- [btnAdd release];
- [super viewDidLoad];
- }
- -(void)BackView{
- // AddViewController *ad=[[AddViewController alloc] init];
- [self dismissViewControllerAnimated:YES completion:nil];
- // [ad release];
- }
- -(void)setValue:(User *)userValue{
- user=userValue;
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- @end
AddViewController.h:
- #import <UIKit/UIKit.h>
- #import "UserDelegate.h"
- @interface AddViewController : UIViewController<UITextFieldDelegate>{
- id<UserDelegate> deleage;
- }
- @property(assign,nonatomic)id<UserDelegate> delegate;
- @end
AddViewController.m:
- #import "AddViewController.h"
- #import "User.h"
- #import "TLViewController.h"
- @interface AddViewController ()
- {
- UITextField *tfname;
- UITextField *tfpassword;
- }
- @end
- @implementation AddViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
- {
- self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
- if (self) {
- // 下一个界面的返回按钮
- UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
- temporaryBarButtonItem.title = @"返回";
- self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
- [temporaryBarButtonItem release];
- }
- return self;
- }
- @synthesize delegate;
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- UILabel *lname = [[UILabel alloc]initWithFrame:CGRectMake(10, 40, 100, 30)];
- //设置显示文字
- lname.text = @"用户名:";
- //设置字体:粗体,正常的是 SystemFontOfSize
- lname.font = [UIFont boldSystemFontOfSize:20];
- //设置文字颜色
- lname.textColor = [UIColor blackColor];
- lname.textAlignment=NSTextAlignmentRight;
- [self.view addSubview:lname];
- [lname release];
- UILabel *lpassword = [[UILabel alloc]initWithFrame:CGRectMake(10, 80, 100, 30)];
- //设置显示文字
- lpassword.text = @"密 码:";
- //设置字体:粗体,正常的是 SystemFontOfSize
- lpassword.font = [UIFont boldSystemFontOfSize:20];
- //设置文字颜色
- lpassword.textColor = [UIColor blackColor];
- lpassword.textAlignment=NSTextAlignmentRight;
- [self.view addSubview:lpassword];
- [lpassword release];
- tfname= [[UITextField alloc] initWithFrame:CGRectMake(110, 40, 200, 30)];
- [tfname setBorderStyle:UITextBorderStyleRoundedRect]; //外框类型
- tfname.placeholder = @"请输入用户名"; //默认显示的字
- tfname.delegate = self;
- [self.view addSubview:tfname];
- [tfname release];
- tfpassword= [[UITextField alloc] initWithFrame:CGRectMake(110, 80, 200, 30)];
- [tfpassword setBorderStyle:UITextBorderStyleRoundedRect]; //外框类型
- tfpassword.placeholder = @"请输入密码"; //默认显示的字
- tfpassword.delegate = self;
- tfpassword.secureTextEntry = YES; //密码
- [self.view addSubview:tfpassword];
- [tfpassword release];
- UIButton *btnAdd=[[UIButton alloc] initWithFrame:CGRectMake(10, 130, 300, 30)];
- [btnAdd setTitle:@"登 陆" forState:UIControlStateNormal];
- [btnAdd setTitle:@"登陆中......" forState:UIControlStateHighlighted];
- [btnAdd setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
- [btnAdd setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
- [btnAdd.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
- btnAdd.backgroundColor = [UIColor redColor];
- [btnAdd addTarget:self action:@selector(LoginUser) forControlEvents :UIControlEventTouchUpInside];
- [self.view addSubview:btnAdd];
- [btnAdd release];
- // 创建自定义的触摸手势来实现对键盘的隐藏
- UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
- tapGr.cancelsTouchesInView = NO;
- [self.view addGestureRecognizer:tapGr];
- }
- //键盘的隐藏
- -(void)viewTapped:(UITapGestureRecognizer*)tapGr{
- [tfname resignFirstResponder];
- [tfpassword resignFirstResponder];
- }
- //登陆并跳转
- -(void)LoginUser{
- NSLog(@"%@",tfname.text);
- TLViewController *tv=[[TLViewController alloc] init];
- self.delegate=tv;
- User *user=[[User alloc] init];
- user.name=tfname.text;
- user.pword=tfpassword.text;
- [self.delegate setValue:user];
- tv.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
- [self presentModalViewController:tv animated:YES];
- [user release];
- [tv release];
- }
- - (BOOL)textFieldShouldReturn:(UITextField *)textField
- {
- [textField resignFirstResponder];
- return YES;
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- @end
6.创建UserDelegate类:
UserDelegate.h:
- #import <Foundation/Foundation.h>
- #import "User.h"
- @protocol UserDelegate <NSObject>
- -(void)setValue:(User *)userValue;
- @end
7.AppDelegate文件:
AppDelegate.h
- #import <UIKit/UIKit.h>
- @class TLViewController;
- @class AddViewController;
- @interface AppDelegate : UIResponder <UIApplicationDelegate>
- @property (strong, nonatomic) UIWindow *window;
- @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
- @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
- @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- //自定义控件
- //@property (strong, nonatomic) TLViewController *viewController;
- @property (strong, nonatomic) AddViewController *addviewController;
- - (void)saveContext;
- - (NSURL *)applicationDocumentsDirectory;
- @end
AppDelegate.m:
- #import "AppDelegate.h"
- #import "TLViewController.h"
- #import "AddViewController.h"
- @implementation AppDelegate
- @synthesize managedObjectContext = _managedObjectContext;
- @synthesize managedObjectModel = _managedObjectModel;
- @synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
- self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
- // Override point for customization after application launch.
- self.window.backgroundColor = [UIColor whiteColor];
- self.addviewController = [[AddViewController alloc] init];
- self.window.rootViewController = self.addviewController;
- [self.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
- {
- // Saves changes in the application's managed object context before the application terminates.
- [self saveContext];
- }
- - (void)saveContext
- {
- NSError *error = nil;
- NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
- if (managedObjectContext != nil) {
- if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
- // Replace this implementation with code to handle the error appropriately.
- // 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.
- NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
- abort();
- }
- }
- }
- #pragma mark - Core Data stack
- // Returns the managed object context for the application.
- // If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- - (NSManagedObjectContext *)managedObjectContext
- {
- if (_managedObjectContext != nil) {
- return _managedObjectContext;
- }
- NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
- if (coordinator != nil) {
- _managedObjectContext = [[NSManagedObjectContext alloc] init];
- [_managedObjectContext setPersistentStoreCoordinator:coordinator];
- }
- return _managedObjectContext;
- }
- // Returns the managed object model for the application.
- // If the model doesn't already exist, it is created from the application's model.
- - (NSManagedObjectModel *)managedObjectModel
- {
- if (_managedObjectModel != nil) {
- return _managedObjectModel;
- }
- NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Login" withExtension:@"momd"];
- _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
- return _managedObjectModel;
- }
- // Returns the persistent store coordinator for the application.
- // If the coordinator doesn't already exist, it is created and the application's store added to it.
- - (NSPersistentStoreCoordinator *)persistentStoreCoordinator
- {
- if (_persistentStoreCoordinator != nil) {
- return _persistentStoreCoordinator;
- }
- NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Login.sqlite"];
- NSError *error = nil;
- _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
- if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
- /*
- Replace this implementation with code to handle the error appropriately.
- 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.
- Typical reasons for an error here include:
- * The persistent store is not accessible;
- * The schema for the persistent store is incompatible with current managed object model.
- Check the error message to determine what the actual problem was.
- 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.
- If you encounter schema incompatibility errors during development, you can reduce their frequency by:
- * Simply deleting the existing store:
- [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
- * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
- @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
- Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
- */
- NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
- abort();
- }
- return _persistentStoreCoordinator;
- }
- #pragma mark - Application's Documents directory
- // Returns the URL to the application's Documents directory.
- - (NSURL *)applicationDocumentsDirectory
- {
- return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
- }
- @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。
ios学习-delegate、传值、跳转页面的更多相关文章
- IOS微信中看文章跳转页面后点击返回无效
经过查找原因发现,下面两种链接,链接1返回不了,链接2可以返回. 链接1:http://mp.weixin.qq.com/s?__biz=MzA5NDY5MzcyNA==&mid=265089 ...
- IOS微信禁用分享跳转页面返回BUG修复
fresh(); function fresh() { let isPageHide = false; window.addEventListener('pageshow', function () ...
- iOS阶段学习第32天笔记(页面传值方法介绍)
iOS学习(UI)知识点整理 一.界面传值方法 1.方法一 Block传值 通过SubView视图的Block向View视图传值改变View视图的背景色 实例代码: 1)SubViewContro ...
- iOS学习——页面的传值方式
一.简述 在iOS开发过程中,页面跳转时在页面之间进行数据传递是很常见的事情,我们称这个过程为页面传值.页面跳转过程中,从主页面跳转到子页面的数据传递称之为正向传值:反之,从子页面返回主页面时的数据传 ...
- [转]iOS学习之UINavigationController详解与使用(二)页面切换和segmentedController
转载地址:http://blog.csdn.net/totogo2010/article/details/7682433 iOS学习之UINavigationController详解与使用(一)添加U ...
- iOS学习之UINavigationController详解与使用(二)页面切换和segmentedController
iOS学习之UINavigationController详解与使用(一)添加UIBarButtonItem是上篇,我们接着讲UINavigationController的重要作用,页面的管理和切换. ...
- [HTML]js实现页面跳转,页面A跳到另一个页面B.以及页面传值(中文)
要实现从一个页面A跳到另一个页面B,js实现就在A的js代码加跳转代码 JS跳转大概有以下几种方式: 第一种:(跳转到b.html)<script language="javascri ...
- webform基础介绍及页面传值(session,cookie)、跳转页面
一,IIS 1.首先知道IIS是个什么东西:它是web服务器软件,安装在服务器上,接受客户端发来的请求,并传送给服务器端,然后响应请求并送回给客户端.类似于饭店里的服务员. 2.会安装IIS——控制面 ...
- 【2017-05-21】WebForm跨页面传值取值、C#服务端跳转页面、 Button的OnClientClick属性、Js中getAttribute和超链接点击弹出警示框。
一.跨页面传值和取值: 1.QueryString - url传值,地址传值 优缺点:不占用服务器内存:保密性差,传递长度有限. 通过跳转页面路径进行传值,方式: href="地址?key= ...
随机推荐
- python用paramiko将执行的结果存入excel表格
一.paramiko 利用paramiko可以远程控制服务器,上传和下载文件. 1.paramiko密码登录方式: #!/usr/bin/env python #coding:utf-8import ...
- 蘑菇街 App 的组件化之路
在组件化之前,蘑菇街 App 的代码都是在一个工程里开发的,在人比较少,业务发展不是很快的时候,这样是比较合适的,能一定程度地保证开发效率. 慢慢地代码量多了起来,开发人员也多了起来,业务发展也快了起 ...
- linux 发邮件
一. centos yum 安装 1. yum install mailx vim /etc/nail.rc 添加网易163邮箱开放的需要认证的smtp服务器: set from=USER@16 ...
- SpringMVC之json数据传递
json是一种常见的传递格式,是一种键值对应的格式.并且数据大小会比较小,方便传递.所以在开发中经常会用到json. 首先看一下json的格式: {key1:value1,key2:value2} 每 ...
- 赵雅智_ListView_BaseAdapter
Android界面中有时候须要显示略微复杂的界面时,就须要我们自己定义一个adapter,而此adapter就要继承BaseAdapter,又一次当中的方法. Android中Adapter类事实上就 ...
- ie11只能用管理员身份打开解决办法
解决IE11只能用管理员身份运行的问题 不知道大家有没有遇到这种情况,在毫不知情的情况下 IE11 突然打不开了,必须要用管理员身份运行才可以打开,而且重置浏览器这个方法也不奏效. 今天本人也遇到了, ...
- android中Canvas使用drawBitmap绘制图片
1.主要的绘制图片方法 //Bitmap:图片对象,left:偏移左边的位置,top: 偏移顶部的位置 drawBitmap(Bitmap bitmap, float left, float ...
- css之选择器
我们都用过jquery,使用jquery选择器,非常的简单,最近刚好有项目上手,拿起书本看了一下,发现好多的东西都忘掉了,好记性不如烂笔头,就将这章内容记录下来,现在我们看下css原生的选择器. 选择 ...
- 从零开始,在windows上用nodejs搭建一个静态文件服务器
从零开始,在windows上用nodejs搭建一个静态文件服务器 首先安装nodejs: 新建一个node文件夹 下载node.exe到该文件夹 下载npm然后解压到该文件夹 现在node文件夹是这样 ...
- Ajax请求传递参数遇到的问题
想写个同类型的,代码未测. 什么是WebAPI?我的理解是WebAPI+JQuery(前端)基本上能完成Web MVC的功能,即:这么理解吧,WebAPI相当于Web MVC的后台部分. 接下来直接上 ...