星空网 > 软件开发 > 操作系统

iOS 页面间传值 之 属性传值,代理传值

手机 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 <NSObject>- (void)sendMessage:(NSString*)message;@end

 

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

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

 

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

1 @interface RootViewController : UIViewController <myDelegete>

 

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 }

 




原标题:iOS 页面间传值 之 属性传值,代理传值

关键词:IOS

IOS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流