iOS 代理页面间的传值 本文主要简单总结代理传值的一般步骤 掌握其基本原理
//
// NextViewController.h
// 代理---C
//
// Created by phyone on 15/7/30.
// Copyright (c) 2015年 phyone. All rights reserved.
//
#import <UIKit/UIKit.h>
//1.声明代理方法
@protocol NextDelegate <NSObject>//
- (void)toLoginWithName:(NSString *)name;//
@end//
@interface NextViewController : UIViewController
//2.声明代理的属性
@property (nonatomic,assign)id<NextDelegate>delegate;//
@property(nonatomic,copy)NSString *titleName;//
@end
//
// NextViewController.m
// 代理---C
//
// Created by phyone on 15/7/30.
// Copyright (c) 2015年 phyone. All rights reserved.
//
#import "NextViewController.h"
@interface NextViewController ()
@end
@implementation NextViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor];
self.title = _titleName;
UIButton *regist = [UIButton buttonWithType:UIButtonTypeCustom];
regist.frame = CGRectMake(200, 200, 100, 50);
regist.backgroundColor = [UIColor purpleColor];
[regist addTarget:self action:@selector(toRegister) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:regist];
}
//3.什么时候触发这个代理方法
- (void)toRegister
{
[self.navigationController popViewControllerAnimated:YES];
// 点击注册成功后触发这个代理
// 4.通过协议的属性 调用代理方法
[self.delegate toLoginWithName:@"登录"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
//
// ViewController.m
// 代理---C
//
// Created by phyone on 15/7/30.
// Copyright (c) 2015年 phyone. All rights reserved.
//
#import "ViewController.h"
//5.导入代理
#import "NextViewController.h"
@interface ViewController ()<NextDelegate>
{
UIButton *button;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"登录";
self.view.backgroundColor = [UIColor grayColor];
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 100, 200, 50);
button.backgroundColor = [UIColor redColor];
[button addTarget:self action:@selector(nextVC) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)nextVC
{
NextViewController *vc = [[NextViewController alloc]init];
// 6.在初始化有代理方法的对象地方 挂上代理
vc.delegate = self;
vc.titleName = @"注册";
[self.navigationController pushViewController:vc animated:YES];
}
// 7.写上代理方法 等待被执行
- (void)toLoginWithName:(NSString *)name
{
[button setTitle:name forState:UIControlStateNormal];
NSLog(@"%@ ok",name);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end