iOS - 使用xib中的tabBarController将数据从一个viewController传递到另一个viewController

时间:2015-03-31 18:57:20

标签: ios objective-c iphone uitabbarcontroller xib

我有一个要求,我需要在按钮点击时将一个字符串值从一个viewController传递给另一个。我还需要使用tabBarController从当前viewController切换到secondViewController。我试过了:

FirstViewController.h

#import“SecondViewController.h”

@property(nonatomic, strong) SecondViewController *secondController;

FirstViewController.m

-(IBAction)go:(id)sender
{
   self.secondController.itemText=@"Demo Text";
   self.tabBarController.selectedIndex=1; //say secondViewController index is 1
}

SecondViewController.h

#import "FirstViewController.h"

@property(nonatomic, strong) NSString *itemText;

SecondViewController.m

  -(void) viewWillAppear (BOOL) animated
    {
       NSLog(@"Comes from FirstViewController: %@",self.itemText);
    }

虽然它切换了viewController,但它打印为空白。代码有什么问题?

2 个答案:

答案 0 :(得分:1)

我的猜测是你的第一个视图控制器" secondController" property与标签栏控制器中指向的对象不同。

正确的做法是访问您的" SecondViewController"来自标签栏中的view controller array property

也就是说,这样的事情:

-(IBAction)go:(id)sender
{
    SecondViewController *secondVC = (SecondViewController *)[self.tabBarController.viewControllers objectAtIndex: 1];
    secondVC.itemText=@"Demo Text";
    self.tabBarController.selectedIndex=1; 
}

答案 1 :(得分:0)

为我工作

-(IBAction)go:(id)sender
{
SecondViewController *secondVC = (SecondViewController *)[self.tabBarController.viewControllers objectAtIndex: 1];
    secondVC.itemText=@"Demo Text";
    self.tabBarController.selectedIndex=1;
}