1

I am coding an app which has a UITableView. I currently have a segue set up set up for the cells in the table as such:

var selectedRow = Int() //global variable so it can be used in both VCs
import UIKit
class TableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "rowSelected", sender: Any?.self)
        selectedRow = indexPath.row
    }
}

The segue works fine. However, in the swift file that controls the viewController (only being used to change the text of a label) does not work appropriately. Here is the code from that VC:

override func viewDidLoad() {
        super.viewDidLoad()  
        firstLabel.text = infoArray[selectedRow]
        print(selectedRow)
    }

The infoArray is set up correctly, but the label is not always change to the correct text... printing selectedRow returns inconsistent numbers... if I hit the first cell it will return 0 sometimes, but it also returns 1, 3, 2, etc... It seems random and isn't correctly returning the current int (and therefore the label text isn't set correctly). Why is this?

1 Answer 1

4

What you're doing is not the way to pass information from one view controller to another. To pass information, pass the information. Instead of dropping the information in a global, implement prepare(for:sender:), where you can get the segue's destination view controller as it prepares, and set a property of the destination view controller.

Sign up to request clarification or add additional context in comments.

4 Comments

I understand the how the prepare(for:) bit would work... just identify the same segue I had used in the initial question. But how do I utilize the sender: to be able to set the appropriate integer to use to select the right index for the array in the destination VC?
That's not what the sender is for. You can just leave it at nil. You know what the appropriate integer is because you are still you (the first view controller). You could put that info in a property of this view controller; that is how you share info between methods of the same view controller. Do you see? It's all a matter of planning ahead. You know you'll need to share this info within this view controller, so this view controller has a property. You know you'll need to share it with the other view controller, so the other view controller has a property.
Or even better, just ask the table view.
Ok I get the concept, but how do I set a property of a viewcontroller?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.