怎么在两个ViewController之间传值

本人原创,转载请注明出处: http://iphone.xiaoxiaostudio.net   如何在ViewController之间传值,我想这是很多刚开始学习iPhone编程朋友,经常问题的一个问题。我就来总结一下吧。
一、前向传值
可以通过属性的方法来实现。举例说明,两个 ViewControllerA 和 ViewControllerB,向ViewControllerB对象传递一个BOOL值数值。 那么在ViewControllerB里添加属性
@property(nonatomic) BOOL *isSomethingEnabled;
然后在ViewControllerA中调用时,传递这个属性
ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib=@"ViewControllerB" bundle=nil]; 
viewControllerB.isSomethingEnabled = YES; 
[self.navigationController pushViewController:viewControllerB animated:YES];
二、后向传值(回传值)
通过委托来实现。 1.在ViewControllerB中定义一个委托
@protocol ViewControllerBDelegate <NSObject>
- (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item;
@end
2.为ViewControllerB添加属性
@property (nonatomic, weak) id <ViewControllerBDelegate> delegate;
3.在需要传值给ViewControllerA的地方调用delegate的方法,其实,就是将事件将由delegate指定的对象来实现。 例如:ViewControllerB里面有一个按钮点击
-(void) buttonClick:(id)sender
{
NSString *itemToPassBack = @"Pass this value back to ViewControllerA";
[self.delegate addItemViewController:self didFinishEnteringItem:itemToPassBack];
}
4.在ViewControllerA里实现该委托的方法
#import "ViewControllerB.h" 
@interface ViewControllerA : UIViewController <ViewControllerBDelegate>
- (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item 
{
 NSLog(@"This was returned from ViewControllerB %@",item); 
}
5.在生成ViewControllerB的对象时,指明该对象的Delegate是由谁来完成,这里是由ViewControllerA来实现的。
ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib=@"ViewControllerB" bundle=nil];
viewControllerB.delegate = self
[[self navigationController] pushViewController:viewControllerB animated:YES];
  这样就完成了两边的交互了。    

转载于:https://www.cnblogs.com/liuxingzi/archive/2012/11/20/3404271.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值