Unable to share data between tab view controllers?

。_饼干妹妹 提交于 2021-02-04 08:10:21

问题


I am making an app where I take in user input and display it as a chart, which requires an array of data. I have managed to save data in an array using core data and I cannot figure out how to share that data from one tab to the other TabViewController.

here is how the data is stored and fetched in the FirstViewController

        let number = Numbers(context: PersistenceService.context)
        number.numberInArray = Int16(numberEnteredInSlider)
        PersistenceService.saveContext()
        testArray.append(Int(Double(number.numberInArray)))

            var numbers  = [Numbers]() // Where Numbers =  NSManaged Class
            var fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Numbers")
            do {try  numbers = PersistenceService.context.fetch(fetchRequest) as! [Numbers]
            for number in numbers {
                print(number.numberInArray)
            }
            }catch {
                print("error")
            }

and here is the output(printed testarray):

SAVED
2
5
6
5

Now I want to share this test array from one view controller to another(chartsViewController) this is what I have tried

class chartsViewController: UIViewController {
    let mainVC = mainViewController(nibName: "mainViewController", bundle: nil)

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print(mainVC.testArray)
        updateGraph()

    func updateGraph() {
        var lineChartEntry  = [ChartDataEntry]() //this is the Array that will eventually be displayed on the graph.

        for i in 0..<mainVC.testArray.count {
            //

            let value = ChartDataEntry(x: Double(i), y: Double(mainVC.testArray[i]))
            // here we set the X and Y status in a data chart entry

            lineChartEntry.append(value)
            // here we add it to the data set
        }}
//only showing the part needed. I have tried the same solution with another array and it worked. 

}

and the output comes as [0] I have also tried making a singleton but that didn't work out.


回答1:


To pass data between tabs on UITabBarController /tabBar, what needs to be done is to have an intermediate. (This is usually the main UITabBarController)

Pic of UITabBarController and the child tabbar

Create a Class and link it to this TabBarController within IB

class BaseTBController: UITabBarController {

  // Provide the variable which we want to pass
  var workoutTitle: String = "Select a Workout"
  
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

Assuming you want to pass data from TabBar2 to TabBar1, then on TabBar2 (in this case, I have it as a UITableView). In the delegate method:

extension VCLibrary: UITableViewDelegate{
  // method to run when table view cell is tapped
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    // prepare to store the data to be passed to another TabBar
    let tabbar = tabBarController as! BaseTBController
    tabbar.workoutTitle = jsonErgWorkouts[indexPath.row].title

    // Automatically select Tab1 after choosing
    self.tabBarController?.selectedIndex = 0

    // Deselect the selected row once we move to Tab1
    tableView.deselectRow(at: indexPath, animated: true)
  }
}

After selecting the data to be passed, the code (above) will automatically switch to Tab1. Within Tab1, the following code is aimed to receive the passed data

override func viewDidAppear(_ animated: Bool) {
    // Obtain Passed in values from BaseTBController
    let tabbar = tabBarController as! BaseTBController

    // populate the Title as passed from Tab2
    workoutTitleLabel.text = tabbar.workoutTitle
}

I learned this from: https://www.youtube.com/watch?v=GL8-eM93EvQ



来源:https://stackoverflow.com/questions/60672819/unable-to-share-data-between-tab-view-controllers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!