user3746428
user3746428

Reputation: 11175

Problems passing variables between view controllers

I am aware that this is extremely basic but I am passing variables between view controllers for the first time and I am having issues.

I'm just trying to take a user's name from a text field on one view controller and display it in a label on another. On the first view controller I have got:

import UIKit

var userName = ""

class FirstViewController: UIViewController, UIPickerViewDelegate {

@IBAction func enterUserDetails(sender : AnyObject) {
    userNameInput.text = userName
}

}

And on the other view controller I have:

override func viewDidLoad() {
    super.viewDidLoad()

userWelcomeMessage.text = "Good \(currentTimeOfDay), \(userName)!"

}

The code runs but I don't get an output from the userName variable.

Any help would be greatly appreciated.

Upvotes: 1

Views: 588

Answers (1)

ilya n.
ilya n.

Reputation: 18826

Change that to

class SecondViewController: UIViewController { 
    ...
    var givenUserName:String!
}  

class FirstViewController: UIViewController, UIPickerViewDelegate {
    var userName = ""

   @IBAction func enterUserDetails(sender : AnyObject) {
        userName = userNameInput.text 
   }

   override func prepareForSegue(...) {
       if (this is your segue) {
           (new view controller).givenUserName = userName
       }
   } 
}

Or if you don't use segues, there's some place where you manually instantiate SecondViewController and you can assign its givenUserName there. But please no global variables.

Upvotes: 1

Related Questions