Swift
This answer shows how to pass data and is updated for Xcode 8 and Swift 3.
Here is how to set up the project.
- Create a project with a
TableView
. See here for a simple example.
- Add a second
ViewController
.
- Control drag from the first view controller with the table view to the second view controller. Choose "Show" as the segue type.
- Click the segue in the storyboard and then in the Attribute Inspector name the Identifier "yourSegue". (You can call it whatever you want but you also need to use the same name in the code.)
- (Optional) You can embed the everything in a Navigation Controller by selecting the first view controller in the storyboard and the going to Editor > Embed In > Navigation Controller.
Code
First View Controller with TableView:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// ...
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Segue to the second view controller
self.performSegue(withIdentifier: "yourSegue", sender: self)
}
// This function is called before the segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// get a reference to the second view controller
let secondViewController = segue.destination as! SecondViewController
// set a variable in the second view controller with the data to pass
secondViewController.receivedData = "hello"
}
}
Second View Controller
class SecondViewController: UIViewController {
@IBOutlet weak var label: UILabel!
// This variable will hold the data being passed from the First View Controller
var receivedData = ""
override func viewDidLoad() {
super.viewDidLoad()
print(receivedData)
}
}
For a more basic example about passing data between View Controllers see this answer.