ios-协议/代理是怎么实现两个页面之间传值


  • 第一页面
    //NextViewController是push进入的第二个页面
    //NextViewController.h 文件
    //定义一个协议,前一个页面ViewController要服从该协议,并且实现协议中的方法
@protocol NextViewControllerDelegate <NSObject>
 - (void)passTextValue:(NSString *)tfText;
@end
@interface NextViewController : UIViewController
@property (nonatomic, assign) id<NextViewControllerDelegate> delegate;
@end

//NextViewController.m 文件
//点击Button返回前一个ViewController页面

- (IBAction)popBtnClicked:(id)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(passTextValue:)]) {
        //self.inputTF是该页面中的TextField输入框
        [self.delegate passTextValue:self.inputTF.text];
    }
    [self.navigationController popViewControllerAnimated:YES];
}
  • 传到第一页
    • 接下来我们在看看ViewController文件中的内容,
      //ViewController.m 文件
@interface ViewController ()<NextViewControllerDelegate>
@property (strong, nonatomic) IBOutlet UILabel *nextVCInfoLabel;
@end

//点击Button进入下一个NextViewController页面

- (IBAction)btnClicked:(id)sender
{
    NextViewController *nextVC = [[NextViewController alloc] initWithNibName:@"NextViewController" bundle:nil];
    nextVC.delegate = self;//设置代理
    [self.navigationController pushViewController:nextVC animated:YES];
}

//实现协议NextViewControllerDelegate中的方法

#pragma mark - NextViewControllerDelegate method
- (void)passTextValue:(NSString *)tfText
{
    //self.nextVCInfoLabel是显示NextViewController传递过来的字符串Label对象
    self.nextVCInfoLabel.text = tfText;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • iOS开发中,页面传值是很常见的,但是页面传值你究竟知道多少呢?笔者这篇文章就是给大家介绍一下页面传值的具体方式,...
    蒲公英少年阅读 6,495评论 10 44
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,291评论 30 472
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,190评论 4 61
  • 从什么都没有的地方/ 到什么都没有的地方/我们/像没发生事一样/自顾地/走在路上/ 离开时的撕心裂肺也许并不...
    拦路雪偏似雪花阅读 1,774评论 0 0
  • 我走在人世间, 刻意在脑袋上顶着一个光环。 你看到的我也许总是那么光鲜。 其实我也有忧伤黑暗的一面, 有些记忆深深...
    JC贾阅读 1,586评论 2 1