使用自定义选项卡栏控制器类在两个视图控制器之间传递数据

时间:2014-11-25 22:50:54

标签: ios xcode swift uitabbarcontroller viewcontroller

我正在尝试使用Tab Bar Controller将数据从一个viewcontroller传递到另一个viewcontroller。我已经实现了一个自定义Tab Bar Controller类。这是我的这个类的代码:

class CustomTabBarControllerClass: UITabBarController, UITabBarControllerDelegate {

    override func awakeFromNib() {
        self.delegate = self;
    }

    func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
        var logView = SecondViewController()
        logView.log.append("Testing 123")
    }

}

正如您在我的代码中所看到的,我正在使用SecondViewController变量创建logView的实例。在我的SecondViewController课程中,我有一个log数组设置,用于保存从CustomTabBarControllerClass课程传递的值。这是我的SecondViewController的代码。

class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var log = [String]()

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return log!.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("logCell", forIndexPath: indexPath) as UITableViewCell

        cell.textLabel.text = log![indexPath.row]

        return cell
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        println(log!) //fatal error: unexpectedly found nil while unwrapping an Optional value
    }

}

在我的viewDidLoad()函数中,我尝试使用println(log!)将日志打印到控制台。此代码运行时,出现以下错误:fatal error: unexpectedly found nil while unwrapping an Optional value。那么我如何在两个viewcontrollers之间传递数据呢?

更新

didSelectViewController函数已使用下面的代码更新,但是,我仍然收到相同的错误消息。

func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
        var logView = self.viewControllers![0] as SecondViewController
        logView.log?.append("Testing 123")
    }

1 个答案:

答案 0 :(得分:7)

您的标签栏控制器已经有一个SecondViewController实例,因此您不应该实例化一个新实例。使用选项卡栏控制器的viewControllers属性来访问您想要的那个(可能是从名称,索引1处的那个)。

class ViewController: UIViewController {

    var log = [String]()

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        println(log)
    }
}

在标签栏控制器中,

class RDTabBarController: UITabBarController , UITabBarControllerDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
    }

    func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
        var logView = self.viewControllers![1] as ViewController
        logView.log.append("Testing 123")
    }

}