How to get selected table view cell row in segue? - ios

I am developing an iOS app using Swift and I have a view controller that segues from a table view cell content view by selecting a cell row or selecting a button inside of that cell row's content view. The original view controller that contains the table view performs a segue on two different occasions: one segue when the cell row itself is selected (segues to an avplayerviewcontroller and plays a video depending on the cell row that was selected) and the second segue happens when you press a button that is inside of the content view of the table view cell. In the first segue, I am able to pass the the cell row that is selected with if let indexPath = self.tableview.indexPathForSelectedRow when I override the first segue. However when I try to pass the cell row that was selected when I try to override the second segue that happens when you press the button it doesn't work. Is this because the button inside of the table view cell doesn't know which row it was selected in? If so, how can I solve this problem, and if not what is a viable solution to solve such issue? Reminder: The "playDrill" segue is trigged when you select a cell row, the "Tips" segue is trigged when you selected a button inside of that same cell row's content view
Code for first segue that happens when you select a cell row (this segue functions as desired):
class DrillsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "playDrill" {
if let indexPath = self.tableView.indexPathForSelectedRow {
if initialRow == 1 {
drillVid = videoURL[indexPath.row]
playerViewController = segue.destination as! PlayerController
playerViewController.player = AVPlayer(playerItem: AVPlayerItem(url: drillVid))
playerViewController.player?.play()
print(indexPath) //prints correct value which is "[0,6]"
}
if initialRow == 3 {
drillVid = videoUrl[indexPath.row]
playerViewController = segue.destination as! PlayerController
playerViewController.player = AVPlayer(playerItem: AVPlayerItem(url: drillVid))
playerViewController.player?.play()
}
Code for second segue that triggers when you select a button inside of the cell's content view (I want this segue to have the value of indexPath as in the first segue, but when I try to use that code it doesn't return the correct value):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Tips" {
if let indexPath = self.tableview.indexPathForSelectedRow {
if initialRow == 1 {
print(indexPath) //the value printed is "6", I want "[0,6]" like the first code block
let tipVC = segue.destination as! KeysController
}
}
}
}

I had this issue also a couple of months ago... finally I was able to solve it with the following tasks:
Create an Outlet and Action of the button in your corresponding TableViewCell
Create a XYTableViewCellDelegate protocol in your TableViewCell.swift file
Define a delegate of your previous created TableViewCell delegate in your TableViewCell class
Define your delegate in cellForRowAt: function of your tableview
Add the delegate to your ViewController class where the TableView is also implemented
Finally just create this function in your ViewController to receive the tapped buttons tableview indexpath
If you need more help on this, please just copy / paste your whole ViewController & TableViewCell class here - We can make then the changes directly in the code.
It should look like the following code:
// FILE VIEWCONTORLLER
// -> 5.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, XYTableViewCellDelegate {
// ... view did load stuff here
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:TripDetailsTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
// -> 4.
cell.delegate = self
// ...
}
// -> 6.
func buttonTappedViewCellResponse(cell: UITableViewCell) {
let indexPath = tableView.indexPath(for: cell)
// do further stuff here
}
}
// FILE TABLEVIEWCELL
// -> 2.
protocol XYTableViewCellDelegate {
func buttonTappedViewCellResponse(cell:UITableViewCell)
}
class XYTableViewCell: UITableViewCell {
// -> 1.
#IBOutlet weak var button: UIButton!
// -> 3.
var delegate: XYTableViewCellDelegate?
// -> 1.
#IBAction func buttonAction(_ sender: Any) {
self.delegate?.buttonTappedViewCellResponse(cell: self)
}
}

You are not able to get the selected index of the selected cell because you are not actually selecting a cell. You are pressing a button inside the cell.
So, what you do is get a reference to the button, get the button's superview (the cell) and then you can get the indexPath of that cell.
class TableViewController: UITableViewController {
var indexPathForButton: IndexPath?
#IBAction func buttonPressed(_ sender: UIButton) {
let button = sender
let cell = button.superview!.superview! as! MyCell // The number of levels deep for superviews depends on whether the button is directly inside the cell or in a view in the cell
indexPathForButton = tableView.indexPath(for: cell)
}
Then in prepare(for segue:)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Tips" {
if initialRow == 1 {
print(indexPathForButton)
let tipVC = segue.destination as! KeysController
}
}
}

I have never used tableview.indexPathForSelectedRow (and while I think it is not good practice, I am not sure if it is responsible for your issue), however one other approach you might try is to send the indexPath object as sender. This would avoid having to check for tableview.indexPathForSelectedRow inside prepareForSegue. For instance,
You can trigger your "playDrill" segue in tableView(UITableView, didSelectRowAt: IndexPath) where you have access to this indexPath and can simply pass it as sender.
When triggering your "Tips" segue, you can also pass this indexPath object as sender. One way to have a reference is to keep the indexPath object when you dequeue your cell and set the button action in ableView(UITableView, willDisplay: UITableViewCell, forRowAt: IndexPath)
Let me know if that helps you! Cheers,
Julien

Related

Passing data from a UITableView to another ViewController depending on what row is selected

I have two ViewControllers one which contains a UITextView and the other one contains a UITableView. I would like my app to pass data for the selected row from the SecondViewController which contains the UITableView to the UITextView in the first ViewController depending on what row the user select. I am using the below code in the firstViewController (Just to give you a bit of history what I have is a UITextView inside the firstViewController and the user have the option of either entering a custom value or exert a longpressgesture then a popover Window get displayed containing the UITableView in the secondViewController. What I would like to achieve is when a row is selected from the popoverView which contains the UItableView the popoverView get closed and the value highlighted in the table get displayed in the UITextView in the firstViewController):
class ViewController: UIViewController, UITextViewDelegate, UIPopoverPresentationControllerDelegate {
#IBOutlet weak var indicativeDesignWorkingLifeTextView: UITextView!
var textInsideIndicativeDesignWorkingLifeTextView: String? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
indicativeDesignWorkingLifeTextView.text = textInsideIndicativeDesignWorkingLifeTextView
indicativeDesignWorkingLifeTextView.attributedText = placeholderTextInIndicativeDesignWorkingLifeTextView
}
}
and the below code in the secondViewController:
#objc func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
func prepare(for segue: UIStoryboardSegue, sender: UITableViewCell?) {
let toFirstViewController = segue.destination as! ViewController
// Pass the selected object to the new view controller.
if let indexPath = self.indicativeDesignWorkingLifeTable.indexPathForSelectedRow {
let selectedRow = years[indexPath.row]
toFirstViewController.textInsideIndicativeDesignWorkingLifeTextView = selectedRow
}
}
}
However, when I run the simulator and select a row from the table nothing happens inside the UITextView in the firstViewController? All what happens is that the firstViewController gets displayed. Any help is much appreciated.
Thanks,
Shadi.
Update your code as:
#objc func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "<set identifier String>", sender: indexPath)
}
func prepare(for segue: UIStoryboardSegue, sender:Any?) {
let toFirstViewController = segue.destination as! ViewController
// Pass the selected object to the new view controller.
if let indexPath = sender as? IndexPath {
print("indexPath - \(indexPath)")
let selectedRow = years[indexPath.row]
print("selectedRow - \(selectedRow)")
toFirstViewController.textInsideIndicativeDesignWorkingLifeTextView = selectedRow
}
}

Issue when performing a segue on a tableview cell

I'm currently learning Swift and trying to perform a segue when the user taps on one of the tableview cells that the app presents. At the moment, whenever the user performs this action, the next view controller is loaded successfully, but it seems that, for some reason, I cannot access any of its UI elements, as each time that I try to do it, I end up getting this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
The error points to the line in which I try to modify the text of one of the labels that are displayed on the next view controller
This is the didSelectRowAt function:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
self.performSegue(withIdentifier: "segue1", sender: self)
}
and this is the prepareForSegue function:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue1" {
let destinationVC = segue.destination as! UserViewController
let selectedRow = tableView.indexPathForSelectedRow!
let selectedCell = tableView.cellForRow(at: selectedRow) as! CustomCell
destinationVC.usernameLabel.text = selectedCell.userName.text //this is where the error is pointing to
destinationVC.bioLabel.text = selectedCell.bio.text
destinationVC.userImage.image = selectedCell.photo.image
}
}
I have no idea about what is causing this problem. My goal is to pass the data from the tapped cell to the next view controller, but this obviously is preventing me from doing so. Does anyone know how I can fix this? Thanks in advance.
Note: I assumed that userName and bio were both UITextFields
Why don't you try something like this?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue1" {
let destination = segue.destination as! UserViewController
// Use of optional binding to make sure an indexPath exists
if let indexPath = tableView.indexPathForSelectedRow {
let cell = tableView.cellForRow(at: IndexPath(row: indexPath.row, section: indexPath.section)) as! CustomCell
// Notice how we are not directly updating the label as before.
destination.usernameText = cell.userName?.text
destination.bioText = cell.bio?.text
}
}
}
Now in UserViewController:
#IBOutlet weak var usernameLabel: UILabel!
#IBOutlet weak var bioLabel: UILabel!
// What we will be passing the text to instead.
var usernameText: String?
var bioText: String?
override func viewDidLoad() {
super.viewDidLoad()
// update the labels with the text from the proper cell.
usernameLabel?.text = usernameText
bioLabel?.text = bioText
}
You can just do the same for your image, just different types. This has to do with the outlets not being allocated when used in prepare(for segue:).
i had great issue with the prepare for segue method when trying the same thing with a UICollectionView. The 2 are very similar so you should be able to change collectionview to tableview easily.
this is what i did... using variable selectedPack
in the view controller you want to segue to you need to set the variable
// passed packName from PackViewController
var selectedPack: String!
then in the viewcontroller you are selecting the cell
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle the segue to JourneyViewController with variable "selectedPack"
// not sure why you need to set the storyboard but it works
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
//create instance of the viewcontroller
let transportJourneyViewController = storyBoard.instantiateViewController(withIdentifier: "JourneyViewController") as! JourneyViewController
//value to pass - has been defined in journey
transportJourneyViewController.selectedPack = INSERT_YOUR_VALUE_TO_PASS
//present the vc
self.present(transportJourneyViewController, animated:true, completion:nil)
}
JourneyViewController is the storyboardID and ClassName of the viewcontroller you want to go to.set in the interface builder.
You'll also need to have the tableviewdatasource and tableviewdelegate defined at the top level of your view controllers and in the storyboard itself.
class JourneyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

Populate table view cells with data from text field in previous view

I want to populate the prototype cells in a table view with information that the user has typed into a text field in a previous view controller. I want to set the title and subtitle of each cell using this data instead of a pre-determined array. How can I pass data from the text field inside a view controller to the title/subtitle section of a table cell view?
Any help is appreciated.
First of all implement this at the point where you want to segue to your TableViewController:
let textFieldString = yourTextField.text ?? ""
performSegueWithIdentifier("exampleID", sender: textFieldString)
Now create the right segue in your StoryBoard!
1) From the whole ViewController to your destination ViewController
2) And don't forget your unique segue-ID
The delegate method prepareForSegue(...) will be called before you perform the segue. In this method you prepare your destination ViewController.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
let targetvc = segue.destinationViewController as? YourTableViewController
if let targetvc = targetvc
{
let yourTextFieldString = sender as? String
if let yourTextFieldString = yourTextFieldString
{
targetvc.yourTextFieldString = yourTextFieldString
}
}
}
When the segue to your destination ViewController is performed, your variable (here in this case "yourTextFieldString") has the previous set data.
class yourTableViewController : UITableViewController
{
var yourTextFieldString = "" // This variable has the previous set data
override func viewDidLoad()
{
super.viewDidLoad()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("yourCellID", forIndexPath: indexPath)
cell.textLabel.text = yourTextFieldString
return cell
}
}
Now adjust your prototype cell (don't forget the right identifier) and you're done.

Can't set UINavigationItem title programatically on initial load

I'm am performing a segue (via storyboard) from a TableViewController (embedded in a NavigationController) to another TableViewController. I.e Selecting a cell and presenting another TableView on which i would like to display the selected cell's text as the next views title.
I am achieving this however not 100% correctly. On the first initial selection of a cell the navigationItem title is not set. Only once i navigate back and then again forward through that same cell, is the title set.
The first snippet is my first viewController that I'm selecting a cell on where I am setting the destinationViewControllers variable with the selected cells title.
var valueToPass:String?
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow!;
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!;
valueToPass = currentCell.textLabel!.text
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "tripSegue") {
// initialize new view controller and cast it as your view controller
let viewController = segue.destinationViewController as! TripTableViewController
// setting the view controllers property that will store the passed value
viewController.passedValue = valueToPass
}
}
The second snippet is from the destinationViewController setting the navigationItem title.
var passedValue: String?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = passedValue
}
This is because prepareForSegue is called before didSelectRowAtIndexPath. So the first time you select a row, valueToPass is nil. prepareForSegue is called while valueToPass is still nil and you pass it, then after you pass that, didSelectRowAtIndexPath is called setting valueToPass to the desired value, which is what's passed the next time you select a row.
You need to do it all in prepareForSegue.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "tripSegue") {
// Get Cell Label
let indexPath = self.tableView.indexPathForSelectedRow!;
let currentCell = self.tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!;
// initialize new view controller and cast it as your view controller
let viewController = segue.destinationViewController as! TripTableViewController
// setting the view controllers property that will store the passed value
viewController.passedValue = currentCell.textLabel!.text
}
}

Swift: Pass UITableViewCell label to new ViewController

I have a UITableView that populates Cells with data based on a JSON call. like so:
var items = ["Loading..."]
var indexValue = 0
// Here is SwiftyJSON code //
for (index, item) in enumerate(json) {
var indvItem = json[index]["Brand"]["Name"].stringValue
self.items.insert(indvItem, atIndex: indexValue)
indexValue++
}
self.tableView.reloadData()
How do I get the label of the cell when it is selected and then also pass that to another ViewController?
I have managed to get:
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("You selected cell #\(indexPath.row)!")
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow();
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
println(currentCell.textLabel.text)
}
I just cant figure out how to pass that as a variable to the next UIViewController.
Thanks
Passing data between two view controllers depends on how view controllers are linked to each other. If they are linked with segue you will need to use performSegueWithIdentifier method and override prepareForSegue method
var valueToPass:String!
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("You selected cell #\(indexPath.row)!")
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow();
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
valueToPass = currentCell.textLabel.text
performSegueWithIdentifier("yourSegueIdentifer", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "yourSegueIdentifer") {
// initialize new view controller and cast it as your view controller
var viewController = segue.destinationViewController as AnotherViewController
// your new view controller should have property that will store passed value
viewController.passedValue = valueToPass
}
}
If your view controller are not linked with segue then you can pass values directly from your tableView function
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("You selected cell #\(indexPath.row)!")
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow();
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
let storyboard = UIStoryboard(name: "YourStoryBoardFileName", bundle: nil)
var viewController = storyboard.instantiateViewControllerWithIdentifier("viewControllerIdentifer") as AnotherViewController
viewController.passedValue = currentCell.textLabel.text
self.presentViewController(viewContoller, animated: true , completion: nil)
}
You asked:
How do I get the label of the cell when it is selected and then also pass that to another ViewController?
I might suggest rephrasing the question as follows: "How do I retrieve the data associated with the selected cell and pass it along to another view controller?"
That might sound like the same thing, but there's an important conceptual distinction here. You really don't want to retrieve the value from the cell label. Our apps employ a MVC paradigm, so when you want to pass data information from one scene to another, you want to go back to the model (the items array), not the view (the text property of the UILabel).
This is a trivial example, so this distinction is a bit academic, but as apps get more complicated, this pattern of going back to the model becomes increasingly important. The string representation from the cell is generally is a poor substitute for the actual model objects. And, as you'll see below, it's just as easy (if not easier) to retrieve the data from the model, so you should just do that.
As an aside, you don't really need a didSelectRowAtIndexPath method at all in this case. All you need is a segue from the table view cell to the destination scene, give that segue a unique identifier (Details in my example), and then implement prepare(for:sender:):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DetailsViewController {
let selectedRow = tableView.indexPathForSelectedRow!.row
destination.selectedValue = items[selectedRow]
}
}
Alternatively, if your segue is between the cell and destination scene, you can also use the sender of the prepare(for:sender:):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DetailsViewController {
let cell = sender as! UITableViewCell
let selectedRow = tableView.indexPath(for: cell)!.row
destination.selectedValue = items[selectedRow]
}
}
But the idea is the same. Identify what row was selected, and retrieve the information from the model, the items array.
The above is Swift 3. For Swift 2.3, please see the previous version of this answer.
Okay..Its been 2 days I was searching for the answer that how could I be able to save the selected UITableViewCell label text data and display that data to an another label on an another View Controller which will come out after tapping on a cell. At last I have completed with the task and its successful. Here is the complete code with steps using Swift.I am using Xcode 6.4.
Step 1.
I have Two class assigned to the storyboard view controllers named "iOSTableViewControllerClass.swift" which is a Table View Controller and "iOSTutorialsViewControllerClass.swift" which is a normal View Controller.
Step 2.
Now make segue from iOSTableViewControllerClass to iOSTutorialsViewControllerClass by Control-dragging on the storyboard area and choose "show" from drop down menu. Click on this highlighted button according to the below image and perform the segue.
Step 3.
Now select the segue by clicking on the storyboard and give it an identifier on the Attributes Inspector. In this case I named it as "iOSTutorials"
Step 4.
Now on this step put a label on your cell as well as on the other view controller and make outlets of them on their corresponding classes.
In my case those are "#IBOutlet weak var iOSCellLbl: UILabel!" and " #IBOutlet weak var iOSTutsClassLbl: UILabel!".
Step 5.
Make a string type variable on the first Table View Controller Class. I did this as "var sendSelectedData = NSString()" also Make a string type variable on the second class. I did this as "var SecondArray:String!".
Step 6.
Now we are ready to go.
Here is the complete Code for first Class --
// iOSTableViewControllerClass.swift
import UIKit
class iOSTableViewControllerClass: UITableViewController, UITableViewDataSource,UITableViewDelegate {
// Creating A variable to save the text from the selected label and send it to the next view controller
var sendSelectedData = NSString()
//This is the outlet of the label but in my case I am using a fully customized cell so it is actually declared on a different class
#IBOutlet weak var iOSCellLbl: UILabel!
//Array for data to display on the Table View
var iOSTableData = ["Label", "Button", "Text Field", "Slider", "Switch"];
override func viewDidLoad() {
super.viewDidLoad()
//Setting the delegate and datasource of the table view
tableView.delegate = self
tableView.dataSource = self
//Registering the class here
tableView.registerClass(CustomTableViewCellClassiOS.self, forCellReuseIdentifier: "CellIDiOS")
//If your using a custom designed Cell then use this commented line to register the nib.
//tableView.registerNib(UINib(nibName: "CellForiOS", bundle: nil), forCellReuseIdentifier: "CellIDiOS")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return iOSTableData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellIDentifier = "CellIDiOS"
//In this case I have custom designed cells so here "CustomTableViewCellClassiOS" is the class name of the cell
var cell:CustomTableViewCellClassiOS! = tableView.dequeueReusableCellWithIdentifier(CellIDentifier, forIndexPath: indexPath) as? CustomTableViewCellClassiOS
if cell == nil{
tableView.registerNib(UINib(nibName: "CellForiOS", bundle: nil), forCellReuseIdentifier: CellIDentifier)
cell = tableView.dequeueReusableCellWithIdentifier(CellIDentifier) as? CustomTableViewCellClassiOS
}
//Here we are displaying the data to the cell label
cell.iOSCellLbl?.text = iOSTableData[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("You selected cell #\(indexPath.row)!")
// Get Cell Label text here and storing it to the variable
let indexPathVal: NSIndexPath = tableView.indexPathForSelectedRow()!
println("\(indexPathVal)")
let currentCell = tableView.cellForRowAtIndexPath(indexPathVal) as! CustomTableViewCellClassiOS!;
println("\(currentCell)")
println("\(currentCell.iOSCellLbl?.text!)")
//Storing the data to a string from the selected cell
sendSelectedData = currentCell.iOSCellLbl.text!
println(sendSelectedData)
//Now here I am performing the segue action after cell selection to the other view controller by using the segue Identifier Name
self.performSegueWithIdentifier("iOSTutorials", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//Here i am checking the Segue and Saving the data to an array on the next view Controller also sending it to the next view COntroller
if segue.identifier == "iOSTutorials"{
//Creating an object of the second View controller
let controller = segue.destinationViewController as! iOSTutorialsViewControllerClass
//Sending the data here
controller.SecondArray = sendSelectedData as! String
}
Here is the complete code for the second Class..--
// iOSTutorialsViewControllerClass.swift
import UIKit
class iOSTutorialsViewControllerClass: UIViewController {
//Creating the Outlet for the Second Label on the Second View Controller Class
#IBOutlet weak var iOSTutsClassLbl: UILabel!
//Creating an array which will get the value from the first Table View Controller Class
var SecondArray:String!
override func viewDidLoad() {
super.viewDidLoad()
//Simply giving the value of the array to the newly created label's text on the second view controller
iOSTutsClassLbl.text = SecondArray
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I do it like this.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedName = nameArray[indexPath.row]
let newView: nextViewName = self.storyboard?.instantiateViewController(withIdentifier: "nextViewName") as! nextViewName
newView.label.text = selectedValue
self.present(newView, animated: true, completion: nil)
}

Resources