【问题标题】:iOS - Pass Data from one viewController to another using tabBarController in xibiOS - 使用 xib 中的 tabBarController 将数据从一个 viewController 传递到另一个 viewController
【发布时间】:2015-03-31 18:57:19
【问题描述】:

我有一个要求,我必须在单击按钮时将字符串值从一个视图控制器传递到另一个视图控制器。我还需要使用 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 但它打印为空白。代码有什么问题?

【问题讨论】:

    标签: ios objective-c iphone uitabbarcontroller xib


    【解决方案1】:

    我的猜测是您的第一个视图控制器的“secondController”属性与标签栏控制器中指向的对象不同。

    正确的做法是从标签栏中的view controller array property 访问您的“SecondViewController”。

    也就是说,是这样的:

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

    【讨论】:

    • 应用程序崩溃了。出现错误:-[UINavigationController setitemText:]: unrecognized selector sent to instance
    • 我删除了代码的第一行(也是错误的),现在一切都应该正确了。如果您在“go”操作的行上设置 Xcode 断点,secondVC 是您期望的视图控制器吗?
    【解决方案2】:

    对我来说很好

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-04
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-25
      • 1970-01-01
      相关资源
      最近更新 更多