2013-01-19 38 views
0

我有一个我正在处理的项目,其中涉及UITabBarController中的3个选项卡(全部在故事板中完成)。在UITabBarController/UIViewControllers之间移动一个值

每个选项卡运行不同的视图控制器。

我有一个按钮在选项卡1上执行计算并在文本框中返回结果。我需要它,当我点击计算时,结果也会在标签2中的文本框中返回。

我不太确定如何在UIViewController之间传递数据,因此不胜感激。

+0

你可以使用nsuserdefaults来存储该值并从nsuserdefaults中获取它以显示在标签2中。希望它能帮助你。 – Exploring

+0

你可以检查我的答案在这里:http://stackoverflow.com/questions/14291043/how-to-pass-value-to-another-controller-view-in-xcode/14291197#14291197 – Bhavin

+0

可能重复的[传递数据在视图控制器之间](http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) –

回答

1

您可以在应用程序委托中定义一个变量,并将结果存储在该变量中。一旦你切换了类,你可以通过创建appDelegate的一个实例并将它赋给你的文本字段来在你的类中获取这个值。

正如Sanjit所说,NSUserDefaults也是一个非常方便和干净的方法来实现这一点。

谢谢。

1

如果您不是真的需要存储计算值,而只是通知tab2中的其他控制器该值已更改,则可以使用NSNotificationCenter来发布NSNotification
当您在tab2中初始化控制器时,您需要将其添加为通知的观察者。

类似的东西:
在TAB1:

NSNumber *value = nil; // the computed value 
[[NSNotificationCenter defaultCenter] 
postNotificationName:@"com.company.app:ValueChangedNotification" 
object:self 
userInfo:@{@"value" : value}]; 

在TAB2:注册为观察者(在init或viewDidLoad中的方法)

[[NSNotificationCenter defaultCenter] 
addObserver:self 
selector:@selector(valueChanged:) 
name:@"com.company.app:ValueChangedNotification" 
object:nil]; 

该方法将被调用时,通知已发布:

- (void)valueChanged:(NSNotification *)note 
{ 
    NSDictionary *userInfo = note.userInfo; 
    NSNumber *value = userInfo[@"value"]; 
    // do something with value 
} 

别忘了请从观察员控制器viewDidUnload或更早:

[[NSNotificationCenter defaultCenter] removeObserver:self]; 
2

按vshall说,你可以做到这一点的东西像波纹管: -

yourAppdelegate.h

@interface yourAppdelegate : UIResponder <UIApplicationDelegate,UITabBarControllerDelegate> 
{ 
     NSString *myCalResult; 
} 
@property (nonatomic,retain) NSString *myCalResult; 

yourAppdelegate。 m

@implementation yourAppdelegate 
@synthesize myCalResult, 

yourCalclass.h

#import "yourAppdelegate.h"

@interface yourCalclass : UIViewController 
{ 
yourAppdelegate *objAppdelegate; 
} 

yourCalclass。米

- (void)viewDidLoad 
{ 
    objAppdelegate = (yourAppdelegate *) [[UIApplication sharedApplication]delegate]; 
    [super viewDidLoad]; 
} 

-(IBAction)ActionTotal 
{ 
objAppdelegate.myCalResult=result; 
} 

现在结果存储在objAppdelegate.myCalResult您可以在另一个选项卡使用这个变量与创建yourAppdelegat的对象。希望它可以帮助你