协议传值
A(ViewController)界面传值到B(SecondViewController)界面,首先在A.h文件中定义一个代理协议,一个代理对象
这里在代理协议中定义了一个协议函数changeColor:
- A.h
#import <UIKit/UIKit.h>
//
@protocol SecondDelegate <NSObject>
//改变颜色的背景函数
- (void) changeColor: (UIColor* ) color ;
@end
@interface ViewController : UIViewController
//定义一个代理对象
//代理对象会执行协议函数
//通过代理对象实现协议函数,达到代理对象改变本身属性的目的
//代理对象一定要实现代理协议
@property (assign, nonatomic) id<SecondDelegate> delegate ;
@end
之后让B来继承A所签订的协议,并且完成协议函数的具体内容
然后将当前控制器作为代理对象赋值
- B.h
#import <UIKit/UIKit.h>
#import "ViewController.h"
@interface SecondViewController : UIViewController <SecondDelegate> //继承了协议
//协议函数
- (void) changeColor:(UIColor *)color ;
@end
- B.m
//下面是一个点击触发的事件函数中的三行代码
//定义一个ViewController类对象
ViewController* viewController = [[ViewController alloc] init] ;
//将当前的控制器作为代理对象赋值
viewController.delegate = self ;
//推出视图控制器viewController
[self.navigationController pushViewController:viewController animated:YES] ;
B完成的协议函数
//编写协议函数内容
- (void) changeColor:(UIColor *) color {
self.view.backgroundColor = color ;
}
- A.m
//一个按钮的点击事件函数,点击按钮触发代理事件
- (void) pressChange {
//代理对象调用事件函数
[_delegate changeColor:[UIColor blueColor]] ;
}
如上即可实现在A中改变了B的背景颜色。
属性传值
如果是从A(ThirdViewController)向B(FourthViewController)传值,则在B中定义一个属性,该属性用来接收在A.m文件中的赋值操作:
//要传值的变量
NSInteger tag0 = 100 ;
//定义一个要传向的对象
FourthViewController* fourthViewController = [[FourthViewController alloc] init] ;
//该对象用属性temp接收了传过来的值
fourthViewController.temp = tag0 ;
在B.h中定义了一个接收属性:
//用于接收值的属性
@property (nonatomic, assign) NSInteger temp ;
此时,在A.m中定义的B(FourthViewController)类的temp属性,已经被赋值为100了。