Passing data from a ViewController to a TabViewCon

2020-08-04 10:28发布

问题:

I would like to know what the most efficient way is to pass a variable (say: a string) from one regular ViewController to a TabViewController. (NOT iOS => ONLY OSX) I've been searching and trying different stuff and I know there is the "prepareForSegue" function, but I can't seem te get it working for a Tab View. (I'm trying to pass over 50-70 vars to the next view btw) Is there no way to create a separate file in which I can store all my vars and then import it in the new view controller? I know this works in objective c. I tried a similar way to do it in Swift but the values just don't seem te remain stored in the vars when I call them in the second view controller.

Pls don't start linking to tutorials for regular view controllers because I've already read 10 of them and none of them seem to help.

I've also downloaded the Swift manual and checked the documentation in Xcode and it's just unclear to me.

PS: X-code is pure and utter sh*t. I thought that something from apple would be more accessible then this useless piece of IDE. Just wanted to ventilate that...

回答1:

Althought you find your answer, here is way to do it with Swift

import Cocoa

@objc protocol SomeDelegate {
    func passData(sender: ViewController, data: String)
}

class ViewController: NSViewController {

    weak var delegate: SomeDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        if let myTabViewController = parentViewController as? MyTabViewController {
            self.delegate = myTabViewController
        }
    }

    @IBAction func buttonPressed(sender: AnyObject) {
        delegate?.passData(self, data: "Hello, world!")
    }
}

And in your tab view controller:

class MyTabViewController: NSTabViewController, SomeDelegate {

    func passData(sender: ViewController, data: String) {
        print("Data is \(data)")
    }
}