例如:我们要将A界面的值传到B界面,下面简单总结一下属性传值和协议传值
一、属性传值
例如我们需要将ViewController.m(A界面)中的值传到SecondViewController.m(B界面)中
属性传值的过程:
(1) 先在SecondViewController.h中声明用于接收传值的相应属性 (2) 在ViewController.m中定义所需要发送值的变量或者在ViewController.h中声明所需要发送值的属性(即在A界面中定义所要发送的值) (3) 在ViewController.m(B界面)中定义一个SecondViewController *类型的对象 (4) 在ViewController.m(B界面)中将所要发送值的变量赋值给新建的SecondViewController *类型的对象的相应属性
代码如下:
在SecondViewController.h中:
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
@property (nonatomic, assign) NSUInteger testTag;
@end
在ViewController.m中:
NSUInteger tag = 101;
SecondViewController *SecondView = [[SecondViewController alloc] init];
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文件中:
#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 alloc] init];
viewController.delegate = self;
[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界面)的背景颜色
|