代理传值(回调传值)

一、在输入值的类的.h文件中声明一个到代理,并声明一个代理方法;

#import <UIKit/UIKit.h>

//声明一个AViewControllerDelegate 协议

@protocol AViewControllerDelegate<NSObject>

//@optional 为可选方法,如果不写则默认为必写方法

@optional

//声明代理方法

-(void)transValue:(NSString *)string;

@end

@interface AViewController: UIViewController

//找一个代理,并将其声明为属性

@property(nonatomic,assign)id<AViewControllerDelegate>delegate;

 

@end


二、在需要传值的页面的类的.m文件实现切换到输入值的页面,并实现传值方法

#import "ViewController.h"

//导入输入值的页面

#import "AViewController.h"

//遵守协议

@interface ViewController ()<AViewControllerDelegate>

//将需要传值的lable定义成属性

@property (weak, nonatomic) IBOutletUILabel *lable;

@end

 

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do anyadditional setup after loading the view, typically from a nib.

}

//实现点击按钮切换页面

- (IBAction)push:(id)sender {

    UIStoryboard *storyboard=[UIStoryboard storyboardWithName:@"Main" bundle:nil];

    AViewController *aViewController =[storyboard instantiateViewControllerWithIdentifier:@"AViewController"];

    aViewController.delegata = self;

    [self presentViewController:aViewController animated:YES completion:^{

       

    }];

}

//实现传值方法

-(void)transValue:(NSString *)string{

    self.lable.text =string;

}

 

- (void)didReceiveMemoryWarning{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end


三、在输入值的页面的.m文件实现点击按钮回到原页面,并传值

#import "AViewController.h"

@interface AViewController ()

//定义输入值的textField为属性

@property (weak, nonatomic) IBOutlet UITextField *textField;

@end

@implementation AViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do anyadditional setup after loading the view.

}

//实现点击按钮回原页面,并传值的方法

- (IBAction)pop:(id)sender {

//判断delegate是否存在,以及是否遵守协议

    if (self.delegata &&[self.delegata conformsToProtocol:@protocol(AViewControllerDelegate)]){

        [self.delegata transValue:self.textField.text];

    }

    [selfdismissViewControllerAnimated:YES completion:^{

    }];

}

- (void)didReceiveMemoryWarning{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark - Navigation

// In a storyboard-based application, youwill often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender {

    // Get the new viewcontroller using [segue destinationViewController].

    // Pass the selectedobject to the new view controller.

}

*/

@end





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值