Home > Blockchain >  How do i use var from another ViewController?
How do i use var from another ViewController?

Time:02-25

i have empty var and then i need to pass value to it from textField

class ViewController: UIViewController, UITextFieldDelegate {
   
    @IBOutlet weak var textFieldToken: UITextField!
    public var authToken = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    
    @IBAction func signInButton(_ sender: Any) {
        authToken = self.textFieldToken.text!
        print(authToken)
    }

Then i need to use "authToken" in another controller, but it is always nil, how do i use it?

class ReposViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    var tokens = ViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        print(tokens.authToken)

    }

Thank you!

CodePudding user response:

Try This:

class ViewController: UIViewController, UITextFieldDelegate {
   
    @IBOutlet weak var textFieldToken: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func signInButton(_ sender: Any) {
        Controller.sharedInstance.token = self.textFieldToken.text ?? ""
        print(Controller.sharedInstance.token)
    }
}

class ReposViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        print(Controller.sharedInstance.token)
    }
}

//Singelton class
class Controller {

    private static var privateSharedInstance: Controller?
    static var sharedInstance: Controller {
        if privateSharedInstance == nil {
            privateSharedInstance = Controller()
        }
        return privateSharedInstance!
    }
    private init() { }

    var token: String = ""
}
  • Related