Pass variables from one ViewController to another in Swift

前端 未结 3 1280
一整个雨季
一整个雨季 2020-12-02 00:45

I have a calculator class, a first ViewController to insert the values and a second ViewController to show the result of the calculation. Unfortunately I get a error called

相关标签:
3条回答
  • 2020-12-02 01:03

    I think the issue here is, you are trying to set the UI component (here, its the label : myResultLabel)

    When segue is fired from first view controller, the second view has not yet been initialized. In other words, the UI object "myResultLabel" is still nil.

    To solve this, you will need to create a local string variable in second controller. Now, set that string to what you are trying to display, and finally, set the actual label in "viewDidLoad()" of the second controller.

    Best Regards, Gopal Nair.

    0 讨论(0)
  • 2020-12-02 01:06

    In Swift, everything is public by default. Define your variables outside the classes:

    import UIKit
    
    var placesArray: NSMutableArray!
    
    class FirstViewController: UIViewController {
    //
    ..
    //
    }
    

    and then access it

    import UIKit
    
    class TableViewController: UITableViewController {
    //
    placesArray = [1, 2, 3]
    //
    }
    
    0 讨论(0)
  • 2020-12-02 01:09

    The problem here is that the FirstViewController has no reference to the instance of SecondViewController. Because of this, this line:

    secondViewController.setResultLabel(myResult)
    

    does nothing (except probably causing the Can't unwrap Optional.None error). There are a few ways to solve this problem. If you are using storyboard segues you can use the -prepareForSegue method of UIViewController. Here is an example:

    In FirstViewController:

    override func prepareForSegue(segue: UIStoryboardSegue!,sender: AnyObject!){         
      //make sure that the segue is going to secondViewController
      if segue.destinationViewController is secondViewController{
        // now set a var that points to that new viewcontroller so you can call the method correctly
        let nextController = (segue.destinationViewController as! secondViewController)
        nextController.setResultLabel((String(myResult)))
      }
    }
    

    Note: this code will not run as is because the function has no access to the result variable. you'll have to figure that out yourself :)

    0 讨论(0)
提交回复
热议问题