iOS 代理传值

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值