美文网首页
iOS代理回传

iOS代理回传

作者: Mr_Dragonn | 来源:发表于2016-07-18 11:15 被阅读63次

    在第二个页面.h文件中:

    #import <UIKit/UIKit.h>
    //1.声明协议,习惯命名方式为 类型+Delegate
    //2.@pro不允许紧贴着#import写,没有代码提示
    //一.代理回传第一步,声明协议
    @protocol NextViewControllerDelegate <NSObject>
    -(void)showText:(NSString *)text;
    @end
    
    @interface NextViewController : UIViewController
    //二.代理回传第二步,声明 协议类型的属性
    @property(nonatomic) id<NextViewControllerDelegate> delegate;
    @end
    

    在第二个页面的.m中

    #import "NextViewController.h"
    
    @interface NextViewController ()
    
    @end
    
    @implementation NextViewController
    - (IBAction)clickReturn:(UITextField *)sender {
    //三.代理回传第三步,在适当的位置调用协议方法
        [_delegate showText:sender.text];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view from its nib.
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    

    在第一个页面.m文件中:

    #import "MyViewController.h"
    #import "NextViewController.h"
    //四.代理回传第四步,引入协议
    @interface MyViewController ()<NextViewControllerDelegate>
    @property (weak, nonatomic) IBOutlet UILabel *label;
    @end
    @implementation MyViewController
    - (IBAction)click:(id)sender {
        NextViewController *nextVC = [NextViewController new];
    //五.代理回传第五步,设置当前视图控制器为 下一页的 代理
        nextVC.delegate = self;
        [self presentViewController:nextVC animated:YES completion:nil];
    }
    //六.代理回传第六步,引入协议方法
    - (void)showText:(NSString *)text{
        _label.text = text;
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.view.backgroundColor = [UIColor greenColor];
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    
    
    @end
    

    相关文章

      网友评论

          本文标题:iOS代理回传

          本文链接:https://www.haomeiwen.com/subject/ermpjttx.html