Update a variable in a TableViewController

纵然是瞬间 提交于 2019-12-13 05:01:27

问题


I need to update a variable in a TableViewController and I can't find the way to do it, can someone explain me why this is not working please? I'm getting mad.

From my view controller this is the code I'm running:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let TV = storyboard.instantiateViewControllerWithIdentifier("tbController") as myTableViewController
TV.x = "test"

And then, from the TableViewController class:

class myTableViewController: UITableViewController {
 var x:String!
 override func viewDidLoad() {
     super.viewDidLoad()
     println("Value of x is: \(self.x)")
 }
}

And the printed value is: nil

Why? What is wrong with that? I don't understand :-(

Updated Picture


回答1:


First, give the segue between the ViewController and the TableViewController an identifier (Example: "TableViewSegue"

Then in the ViewController, use prepareForSegue to pass data from ViewController to TableViewController

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
    if segue.identifier == "TableViewSegue" {
        let vc = segue.destinationViewController as myTableViewController
        vc.x = "Test"
    }
}



回答2:


There could be several issues here.

1. You should embed the tableview into the initial viewcontroller and create it as an IBOutlet

Edit: from the updated picture it appears that you want to click the top right button and go to the tableview. Therefore, this is an incorrect statement.

  1. You also need to make your Viewcontroller (either the tableviewcontroller or the main viewcontroller if you chose to follow #1 above) a UITableViewDelegate and UITableViewDataSource
  2. If you are expecting to change the label listed on the image shown, you will need to use label.text = "String" assignment to change what is displayed there
  3. You have not set an initial variable for x inside the tableviewcontroller.

Also, as a point, your order of operations isn't properly set, so it will always display nil. Because if you look at how you built this:

  1. You have a println inside of a viewdidload on the tableview. This variable you are printing has NOT been set yet, so it is nil
  2. You then created an instance of this class. As soon as you created that instance, the viewdidload method fired and it printed a nil line.
  3. THEN you changed the variable via the TV.x method. But there is no println check there so you're not able to see what you did.


来源:https://stackoverflow.com/questions/26533449/update-a-variable-in-a-tableviewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!