·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> iOS页面间传值之属性传值,代理传值

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

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

手机 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 }