0

I´m trying to pass data between TabBarController using this example

Problem is, that the label in ViewController2 won´t update.

Here is the code I´m using:

TabBarController:

import UIKit

class CustomTabBarController: UITabBarController {
    var myInformation: [String ] = []

    override func viewDidLoad() {
        super.viewDidLoad()
}

ViewController1:

class ViewController1: UIViewController {

    var items = [String]()

    @IBOutlet weak var label: UILabel!


    @IBAction func item1(_ sender: UIButton) {
   items += ["Audi"]
        print(items)
    }

override func viewDidLoad() {
        super.viewDidLoad()
    if let tbc = self.tabBarController as? CustomTabBarController {
        tbc.myInformation = items
    }

}

ViewController2

class ViewController2: UIViewController {

    @IBOutlet weak var label: UILabel!


    override func viewDidLoad() {
        super.viewDidLoad()
        if let tbc = self.tabBarController as? CustomTabBarController {

              for item in tbc.myInformation {
                label.text = item
                }
        }
}

I guess, since

if let tbc = self.tabBarController as? CustomTabBarController {
        tbc.myInformation = items
    }

is in viewDidLoad, it won't update when the item1 button is pushed? But X-code won't allow me to put it elsewhere. How should I go about to get the button to update the array?

Catch
  • 153
  • 1
  • 14

1 Answers1

0

I think issue is there in Controller 1:

if let tbc = self.tabBarController as? CustomTabBarController {
    tbc.myInformation = items
}

Because you are calling this in ViewDidLoad, and ViewDidLoad is only call when your view is load in memory. You need to update values when you are appending values in your controller 1's arrays.

you have to update myInformation array in:

@IBAction func item1(_ sender: UIButton) {
    items += ["Audi"]
    if let tbc = self.tabBarController as? CustomTabBarController {
       tbc.myInformation = items //OR// tbc.myInformation.append("Audi")
    }
    print(items)
}