Xcode: Passing Information from UITableViewController to UIViewController - ios

I have a UIViewController which should show me DetailInformations depending on what Cell was pressed in the UITableViewController.
For the moment I am passing them through a sequel:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "show" {
var ctrl = segue.destination as! DetailViewController
ctrl.information = _informationList[id]
}
}
The id variable is set through:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
id = indexPath.row
}
Now in my UIViewController I change the information with:
override func viewDidLoad() {
super.viewDidLoad()
setInformation(i: information)
}
Now my problem is, that if I press, lets say cell 2. It switches to the ViewController and shows Information of cell 1. Than I go back to the tableview and I press cell 3. Then it shows me cell 2.
In short, it seems that the viewController is loaded (with the last information), before it sets the new information.
Is there any better way to solve this?

Try using indexPathForSelectedRow in prepareForSegue as of it looks like that you have created segue from UITableViewCell to the Destination ViewController so that prepareForSegue will call before the didSelectRowAt.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "show" {
var ctrl = segue.destination as! DetailViewController
if let indexPath = self.tableView.indexPathForSelectedRow {
ctrl.information = _informationList[indexPath.row]
}
}
}

I am assuming based on what you are describing is that you used a segue in your Storyboard to link directly from the cell to the detail view controller. This is not what you want to do, as mentioned earlier, because you don't get the order of events you would expect. You could use the delegation design pattern for this, but assuming you want to stick with segues you need to make the "show" segue from the table VC itself to the detail VC. You then manually call the segue from the tableView didSelectRowAt code.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
id = indexPath.row
performSegue(withIdentifier: "show", sender: self)
}
Finally, you could then use an unwind segue when you come back to catch any data changes initiated in the detail VC.

Related

prepare for segue call before tableView didSelectRowAt indexPath iOS

I have 3 VC - VC1, VC2 & VC3
I'm creating an unwind segue where -
VC1 is destination
VC2 is source
So, I've add Marker function in VC1 -
#IBAction func unwindToHomeViewController(_ sender: UIStoryboardSegue) {}
and in VC2 I've created two variable -
var userSelectedPlacesLatitude: Double = 0
var userSelectedPlacesLongitude: Double = 0
which will be updated in tableView -
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.userSelectedPlacesLatitude = suggestedPlacenames[indexPath.row].geometry.coordinates[1]
self.userSelectedPlacesLongitude = suggestedPlacenames[indexPath.row].geometry.coordinates[0]
print("In didSelectRowAt", userSelectedPlacesLatitude, userSelectedPlacesLongitude)
}
and then prepare for segue -
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! VC1
print("In Segue preperation",userSelectedPlacesLatitude, userSelectedPlacesLongitude)
destinationVC.userSelectedPlacesLatitude = self.userSelectedPlacesLatitude
destinationVC.userSelectedPlacesLongitude = self.userSelectedPlacesLongitude
destinationVC.reloadWeatherDataStatus = true
}
But from print value I'm seeing that prepareforSegue is called earlier than didSelectRowAt. Hence I'm not getting expected value in prepareforsugue
In Segue preperation 0.0 0.0
In didSelectRowAt 49.3227937844972 31.3202829593814
Hence 0.0 0.0 is passing all the time to VC1. How can I fix this problem?
The problem you are experiencing results from having at the unwind segue linked directly from the table view cell in your storyboard. As soon as the user taps the row, the unwind segue fires. The didSelectRow(at:) function is called after, but this is too late; You are already back in VC1.
While you can use prepareForSegue to send data to VC1, a better approach is to use the sender passed to unwindToHomeViewController to let VC1 get the data from VC2.
This means that VC2 doesn't need to know anything about VC1. You can also get rid of the reloadWeatherDataStatus property and simply reload the weather data status in the unwind function.
You should:
Remove the segue from the table view row in VC2
In your storyboard, ctrl-drag from the "View controller" icon at the top of VC2 to the "Exit" icon at the top of VC2 and select unwindToHomeViewController
Select the newly created unwind segue and give it an identifier, say unwindToVC1
In VC2 you have
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.userSelectedPlacesLatitude = suggestedPlacenames[indexPath.row].geometry.coordinates[1]
self.userSelectedPlacesLongitude = suggestedPlacenames[indexPath.row].geometry.coordinates[0]
self.performSegue(withIdentifier:"unwindToVC1", sender: self)
}
Remove prepare(for segue: sender:) from VC2
In VC1
#IBAction func unwindToHomeViewController(_ sender: UIStoryboardSegue) {
if let sourceVC = sender.source as? VC2 {
self.userSelectedPlacesLatitude = sourceVC.userSelectedPlacesLatitude
self.userSelectedPlacesLongitude = sourceVC.userSelectedPlacesLongitude
// Do whatever is required to reload the data based on the new location
}
}
Try the code below and let me know if it works -
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let destinationVC = VC1()
destinationVC.userSelectedPlacesLatitude = suggestedPlacenames[indexPath.row].geometry.coordinates[1]
destinationVC.userSelectedPlacesLongitude = suggestedPlacenames[indexPath.row].geometry.coordinates[0]
destinationVC.reloadWeatherDataStatus = true
destinationVC.performSegueWithIdentifier("DestinationSegueName", sender: self)
}
Adding modifications to this answer since some people might have problems with creating the VC instance -
Step 1 - Create a manual segue named "SegueToDestinationVc" from source(VC1) to destination(VC2) view controller and write this code in source view controller -
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "SegueToDestinationVc") {
let vc = segue.destination as! VC2
vc.dataToPass = someData
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
someData = placeName[indexPath.row]
}
Step 2 - In destination view controller(VC2) has a public property named "dataToPass" and use it.
Happy to help, Thanks.
Happy Coding
Let me know if you need any other help.

Losing row id in tableview before passing data

I have a Navigation controller embedded to a VC called UserDashboardVC. I then have a menu VC and the one option opens another VC with a tableview, ManageAccountVC. When I select the table row I would like it to unwind and populate the data on the UserDashboardVC.
I'm struggling to pass the data back to the UserDashboardVC using unwind segue from ManageAccountVC.
In my UserDashboardVC (root) I have my unwind segue code:
#IBAction func unwindUserDashboardVC(_ unwindSegue: UIStoryboardSegue) {
userCompanyLabel.text = PassCompanyOffice}
In my ManageAccountVC the tableview cell has been connected to Exit unwindUserDashboardVC, this works, when I click on the cell I unwind to UserDashboardVC. I have a function in ManageAccountVC to get the row selected:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
PassCompanyOffice = userAccountArray[indexPath.row].companyOffice!
}
I also have the Prepare function in ManageAccountVC which seems to trigger before I get my row value:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let ConfirmVC = segue.destination as! UserDashboardVC
ConfirmVC.PassCompanyOffice = PassCompanyOffice
}
Why is my unwind segue being performed before my cell row is identified? How do I pass back my data?
You may want to create a class member to hold the selected row and assign that in willSelectRow for the tableview. Then pickup the value in the prepare for Segue or the unwind segue in this case. Put a breakpoint in the unwind segue to determine the state of the selected row variable before using it.
Manual Segue
To separate the cell click action from the segue you will need to remove the exit segue that you made from the tableview cell to the exit.
Then create a manual segue from the view controller to the exit icon. Give that segue an identifier and then call the performSegue with identifier (using the exitSegueIdentifier)
This way you separate the two actions. You can click on the table without exiting. In your code base you can decide when you want to call the performSegue and actually close the VC using the manual exit segue.
As #Tommie C. mentioned, my issue was with the TableViewCell that was linked to the Storyboard Exit. I removed that segue and added a manual Exit seguel by doing this:
Make sure the above is made identifiable, in this case it is "loadDashboardSegue". The Prepare function has the segue identifier name "loadDashboardSegue":
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "loadDashboardSegue" {
let ConfirmVC = segue.destination as! UserDashboardVC
ConfirmVC.PassCompanyOffice = PassCompanyOffice
}
}
Lastly, you action the segue manually in the tableview row select:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
PassCompanyOffice = userAccountArray[indexPath.row].companyOffice
performSegue(withIdentifier:"loadDashboardSegue", sender: self)
}

Passing value from table view controller to view controller

I tried to pass the value of the cell that the user clicks on to another view controller.
Here is my code.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
productDisplayed = currentProductList[indexPath.row] as? Product
performSegue(withIdentifier: "ProductDetailSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if ( segue.identifier == "AddProductSegue"){
let controller: AddProductViewController = segue.destination as! AddProductViewController
controller.delegate = self
}
if ( segue.identifier == "ProductDetailSegue"){
let controller: ProductDetailsViewController = segue.destination as! ProductDetailsViewController
controller.currentProduct = productDisplayed
}
}
Firstly, I didn’t write “performSegue()”.
The issue I met is that the screen will be transferred firstly rather than assign the value to “productDisplayed”, which means the object “currentProduct” in the second VC is nil.
Then I added “performSegue()”.
It still didn’t work. The thing is the second screen was displayed twice. The first time is same with the picture above. And the second time is correct.
But when I tried to click the back button on the left top. It returned to the nil page rather than the ProductDetail page. The screenshot is as follows.
It seems like "prepare" method always being called first then the tableView. How to change the order? If can, this should be fixed I think.
Hope to get your help.
Thank you.
Cause of Problem:
In your storyboard, you may have bound, ProductDetailsViewController with UITableViewCell directly.
It means, upon click/selection of row, it will perform segue (navigation) operation directly.
At the same time, programatically you perform navigation operation using performSegue(withIdentifier: "ProductDetailSegue", sender: self)
Solution:
You have two ways to solve this issue.
I recommend - In your story board, switch segue connection from UITableViewCell to UIViewController (Remove segue connection from UITableViewCell and attach the same segue connection with UIViewController of your tableview)
In your source code, delete/remove this line performSegue(withIdentifier: "ProductDetailSegue", sender: self) and handle data transmission from this function override func prepare(for segue: UIStoryboardSegue, sender: Any?)

Passing Data Between Controllers in Swift

I want to passing data between TableViewController and ViewController
the program does not go into the method
My swift code:
override func unwind(for unwindSegue: UIStoryboardSegue, towardsViewController subsequentVC: UIViewController) {
let destView : ViewController = unwindSegue.destination as! ViewController
destView.min = Int(minTable)
destView.tableText = unitsText
}
I take data:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let tableCell = moneyArray[indexPath.row]
minTable = tableCell.val
unitsText = tableCell.name
let _ = navigationController?.popViewController(animated: true)
}
Adn my Table Code:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! TableViewCell
let tableShow = moneyArray[indexPath.row]
cell.nameCurrency?.text = tableShow.name
cell.valueCarrency?.text = "\(tableShow.val)"
return cell
}
You are using popViewController on your didSelectRow, that means that you are returning on your navigation controller and not pushing a unwind segue or any segue, so you cant use prepareForSegue/unwind method.
One correct way of solving this is using delegation.
You can find more information about that here:
Passing data back from view controllers Xcode
But if you want to use unwind segue, you will have to write your unwind method on the previous viewController, not your current. Also you will need to use the method performSegue with the identifier of your unwind segue.
You can see more information about unwind segues here:
What are Unwind segues for and how do you use them?
If you want to open a detail view controller when the user clicks on a cell in your main table view controller then the proper way to pass data is by using something like the following:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "MyDetailView") {
// pass data to next view
if let viewController: MyDetailsViewController = segue.destinationViewController as? MyDetailsViewController {
viewController.units = mySelectedTableCell.unitsName
}
}
}
Full docs here.

How to create View Controller and its Controls programmatically in Swift?

I am populating a table view as menu using a custom table view cell and using it as menu.I am able to navigate to other views using navigation controller.
But I want to create views and its controls programmatically. Is it possible?
Can anyone please share me an example. Please find my menu structure in the following image.
This is how i did it. It works like a charm!!!
func tableView(_tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//Remove the below line from this function as it will perform segue.
//performSegue(withIdentifier: "DynamicSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
// This will actually perform your segue
var DestViewController = segue.destination as! DynamicSuperView
let selectedRow = tableView.indexPathForSelectedRow?.row
DestViewController.labelText = names[selectedRow!]
}

Resources