Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
979 views
in Technique[技术] by (71.8m points)

swift - Unable to share data between tab view controllers?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...