iOS 页面间传值 之 属性传值,代理传值
发布日期:2021-08-26 09:44:24 浏览次数:4 分类:技术文章

本文共 1552 字,大约阅读时间需要 5 分钟。

hot3.png

手机 APP 运行,不同页面间传值是必不可少,传值的方式有很多(方法传值,属性传值,代理传值,单例传值) ,这里主要总结下属性传值和代理传值.

属性传值:属性传值是最简单,也是最常见的一种传值方式,但其具有局限性(一般用于将第一个页面的值传递到第二个页面,但无法从第二个页面传到第一个页面),

  向SecondViewController传值:SecondViewController 设置属性 sendMessage

1 - (void)rightButtonAction:(UIBarButtonItem *)sender{ 2     SecondViewController *secondVC = [[SecondViewController alloc]init]; 3     secondVC.sendMessage = self.rootView.textField.text; 4     [self.navigationController pushViewController:secondVC animated:YES]; 5 }

 

 

代理传值:较难,不易理解,通常用于在第二个页面向第一个页面传值.一般分为六步

(例子采用 navigationController 跳转页面)

1.声明协议 (写在第二个页面)

@protocol myDelegete 
- (void)sendMessage:(NSString*)message; @end

 

 

2.定义遵守协议的属性 (写在第二个页面) (属性必须用 assign )

@property (nonatomic , assign)id
 delegate;

 

 

3.遵守协议(写在第一个页面)

1 @interface RootViewController : UIViewController 

 

 

4.设置代理 (设置代理写在跳转事件内) (写在第一个页面)

 

1 - (void)rightButtonAction:(UIBarButtonItem *)sender{ 2     SecondViewController *secondVC = [[SecondViewController alloc]init]; 3     secondVC.sendMessage = self.rootView.textField.text; 4     [self.navigationController pushViewController:secondVC animated:YES]; 5     //代理传值第四步6     secondVC.delegate = self; 7     8 }

 

 

 

 

5.实现协议方法 (写在第一个页面)

 

1 - (void)sendMessage:(NSString *)message{ 2     self.rootView.textField.text = message; 3 }

 

 

 

 

6.实现传值 (写在第二个页面)

1 - (void)leftButtonAction:(UIBarButtonItem *)sender{ 2     [self.navigationController popViewControllerAnimated:YES]; 3     //代理传值第六步:4     [self.delegate sendMessage:self.secondView.textField.text]; 5 }

 

 

转载于:https://my.oschina.net/AngeloTsui/blog/663326

转载地址:https://blog.csdn.net/weixin_33881753/article/details/92439167 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【学习日记】第四天-基本工具使用:TCPDUMP
下一篇:python -- map并发

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年03月27日 17时52分26秒