wades
wades

Reputation: 302

How to pass data in selected cell to another view controller?

The piece of code below prints the content of whichever cell is clicked on in my TableView.

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)  {
    print(self.cell[indexPath.row])
}

I want to use the result that is printed in a label on another ViewController.

How do I get the string value from the function and then use it on on the other view? My thought is to use a global variable but I need to get the string value out first.

Upvotes: 0

Views: 1787

Answers (2)

Agisight
Agisight

Reputation: 1818

At first, when you create a tableView, you have to collect data (string here) of cells in an array or another data collection. And you can get a needed data (strings) with indexPath variable in the method didSelectRowAt. And you can pass the string to another ViewController (let use SecondViewController) with several ways.

Here is an example:

// declaration an array of your strings
var array : [String] = ["First", "Second", "Third", ...]
...
// getting a string from method:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)  {
let string = array[indexPath.row]
print(string)
// next, for example, you need to pass the string to a singleton SecondViewController with static var **main**:
SecondViewController.main?.neededString = string
}

Don't forget update in async DispatchQueue:

DispatchQueue.main.async {
    SecondViewController.main?.updateUI(withString : string)
}

Upvotes: 0

Agisight
Agisight

Reputation: 1818

For example, You can use simple organization of a singleton of another ViewController (SecondScreen) with var main (in case, as usual, when SecondScreen inited via a Storyboard):

class SecondScreen : UIViewController {
    // 1. add this var
    static var main : SecondScreen? = nil

    // 2. Your some UI element
    @IBOutlet weak var textButton: UIButton!

    // 3. add this method
    func updateUI(string : String) {
        textButton.setTitle(string, for: .normal)
    }

    // 4. setting a var
    override func viewDidLoad() {
        if SecondScreen.main == nil {
            SecondScreen.main = self
        }
    }

    // ... another your and standard methods
}

And you can update your SecondScreen like this:

    let v = SecondScreen.main
    v?.updateUI(string: "yourString")

Also I recommend you to call method async:

DispatchQueue.main.async {
    SecondScreen.main?.updateUI(withString : string)
}

I suggest you to learn more about singletons...

Upvotes: 1

Related Questions