例如:我们要将A界面的值传到B界面,下面简单总结一下属性传值和协议传值
一、属性传值
例如我们需要将ViewController.m(A界面)中的值传到SecondViewController.m(B界面)中
属性传值的过程:
(1) 先在SecondViewController.h中声明用于接收传值的相应属性
(2) 在ViewController.m中定义所需要发送值的变量或者在ViewController.h中声明所需要发送值的属性(即在A界面中定义所要发送的值)
(3) 在ViewController.m(A界面)中定义一个SecondViewController *类型的对象
(4) 在ViewController.m(A界面)中将所要发送值的变量赋值给新建的SecondViewController *类型的对象的相应属性
代码如下:
在SecondViewController.h中:
//(假设我们要传ViewController.m中tag的值)
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
//声明用于接收值的属性
@property (nonatomic, assign) NSUInteger testTag;
@end
在ViewController.m中:
//定义要发送值的变量
NSUInteger tag = 101;
//定义一个SecondViewController *类型的对象
SecondViewController *SecondView = [[SecondViewController alloc] init];
//将tag赋值给该(B界面)对象的相应属性
SecondView.testTag = tag;
此时属性传值就算成功了,我们就可以在SecondViewController.m中使用ViewController.m中的tag的值了
二、协议传值
继续接着上面的例子,我们需要将ViewController.m(A界面)中的值传到SecondViewController.m(B界面)中
协议传值的过程:
(1) 首先在ViewController.h文件中定义一个代理协议、协议函数,声明一个代理对象
(2) 在SecondViewController.h文件中继承那个协议并声明协议函数
(3) 在SecondViewController.m文件中编写协议函数的具体内容并将当前的控制器做为代理对象赋值
(4) 在ViewController.m文件中使用代理对象调用事件函数
代码如下:
在ViewController.h文件中:
//假设我们要将ViewController.m中颜色的值传到SecondViewController.m中用来改变SecondViewController(B界面)的背景颜色
#import <UIKit/UIKit.h>
//定义代理协议
@protocol ViewControllerDelegate <NSObject>
//定义一个协议函数,改变背景颜色
- (void) changeColor: (UIColor *) color;
@end
@interface ViewController : UIViewController
//定义一个代理对象
//代理对象会执行协议函数
//通过代理对象实现协议函数,达到代理对象改变本身属性的目的
//代理对象一定要实现代理协议
@property (assign, nonatomic) id<ViewControllerDelegate> delegate;
@end
在SecondViewController.h文件中:
#import <UIKit/UIKit.h>
#import "ViewController.h"
NS_ASSUME_NONNULL_BEGIN
//继承那个协议
@interface SecondViewController : UIViewController <ViewControllerDelegate>
//声明协议函数
- (void) changeColor:(UIColor *)color;
@end
在SecondViewController.m文件中:
//当前例子中下面三行代码写在一个点击触发的事件函数中
//创建一个ViewController *类型的对象
ViewController *viewController = [[ViewController alloc] init];
//将当前的控制器做为代理对象赋值
viewController.delegate = self;
//推出视图控制器ViewController
[self.navigationController pushViewController:viewController animated:YES];
//编写协议函数内容
- (void) changeColor:(UIColor *)color {
self.view.backgroundColor = color;
}
在ViewController.m文件中:
//此例子中调用协议函数写在一个按钮的点击事件函数里
//点击按钮时,触发代理的事件
- (void) pressChange {
//代理对象调用事件函数
[_delegate changeColor:[UIColor redColor]];
}
此时协议传值就完成了,我们也就实现了从ViewController(A界面)改变SecondViewController(B界面)的背景颜色