1.ViewController之间正向传值 (ViewController1传给ViewController2)
利用属性的方法:
在ViewController2中定义一个属性,等ViewController2初始化的时候直接为其属性赋值
SecondViewController *second = [[SecondViewController alloc] init];
second.count = i;
second.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:second animated:YES];
[second release];
2.逆向传值 (ViewController2传给ViewController1)
利用代理的方法:
因为此时要改变viewcontroller1中label的值,所以ViewController1是委托者,委托者需要实现协议中的方法
首先定义一个协议
//MyProtocal.h
#import <Foundation/Foundation.h>
@protocol MyProtocal <NSObject>
- (void)setLabel:(NSString *)str;
@end
ViewController2中定义一个指针指向委托者,其实该指针也就是ViewController1的对象,通过对象调用setLabel:(NSString *)str方法,从而实现ViewController2向ViewController1传值.
3.利用广播的方法
首先发送一个广播
UIColor *color = [UIColor greenColor];
[[NSNotificationCenter defaultCenter] postNotificationName:@"CHANGE_COLOR" object:color];
接收广播
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:@"CHNAGE_COLOR" object:nil];
//实现方法
- (void) change:(NSNotification *)sender
{
UIColor *color = [sender object];
self.view.backgroundColor = color;
}