skip to Main Content

Hi, recently I tried to send a variable from ViewController 1 :

guard let viewController2 = self.storyboard?.instantiateViewController(withIdentifier: "ViewController2") as? ViewController2 else
                {
                    fatalError("Error when trying to get the reference to the Step 2")
                }
        viewController2.testName = TextFieldOutlet.text!

To ViewController2 :

class ViewController2: UIViewController {
    @IBOutlet weak var labelTest: UILabel!
    
    public var testName = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        labelTest.text = testName
    }
    
}

All the code seems to be correct but my label and my variable in the ViewController2 remain empty.

Could someone help me?

2

Answers


  1. Code looks fine, you should debug it.
    print(TextFieldOutlet.text) before setting it to viewController2.testName.
    or use breakpoints to find out the issue.

    Login or Signup to reply.
  2. You can just instead of calling it, you need to trigger it by action that’s why I’ve added a button like in the image and make connection between it and viewController2 and worked with its segue and it worked fine

    The image:
    enter image description here

    Code added in viewController:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
         let viewController2 = segue.destination as! ViewController2
         viewController2.testName = TextFieldOutlet.text!
        
        
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search