0

I am doing an assignment, In ViewController A, I have three cells, Calcium, Alkalinity, Magnesium. I need to update ViewController B based on the cell tapped in ViewController A. i.e if Alkalinity was tapped, the label on ViewController B should say "Alkalinity", if calcium is tapped, ViewController 2 should say calcium etc.

Should I create a segue for each cell? Or can I do this via code?

I tried using a segue but I feel as if it is to many segues... Im thinking to use cell tags?

no error yet

Lirik
  • 3,167
  • 1
  • 30
  • 31
isaacthedev
  • 181
  • 10

3 Answers3

0

Option without segues:

1) In interfaz builder, assign a identifier to ViewControllerB

2) ViewControllerA need conform UITableViewDelegate protocol (or UICollectionViewDelegate if you use UICollectionView)

3) Implement the method tableView(_:didSelectRowAt:) in ViewControllerA

4) In the method, instantiate a ViewControllerB instance, example:

let vc = UIStoryboard(name: "nameofthestoryboard").instantiateViewController(withIdentifier: "ViewControllerB") as! ViewControllerB

5) Get the cell selected with the index path.

let cell = tableview.cellForRow(at: indexPath) as! YourCellType

6) Setup the necessary information to viewControllerB, example:

vc.chemicalElement = cell.chemicalElement

7) Present the ViewControllerB instance that you created.

present(vc, animated: true, completion: nil) 

And that is all.

Rey Bruno
  • 355
  • 1
  • 13
0

If you are using a simple segue to move between view controllers than to pass data from one to the other you can do something like this.

You need to instantiate the title variable in ViewControllerA.

var elementName : String?   

Using the function prepare(for segue: UIStoryboardSegue, sender: Any?)

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if(segue.identifier == "SEGUE IDENTIFIER HERE") {
       var vc = segue.destinationViewController as ViewControllerB 
       vc.title = elementName
    }      
}

You also need to instantiate the title variable in ViewControllerB.

var title : String? 

If you post your code I can give you more specific help otherwise this is the flow you could use to accomplish this task

nix.codes
  • 388
  • 2
  • 20
0

You can create a public variable on viewController B,

public var componentName : String?

then pass the selected value(from did select method) from ViewController A.

let ViewB = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewcontrollerB")
ViewB.componentName = componentName //get this component name from index path
self.navigationController?.show(ViewB, sender: nil)
Sathish
  • 96
  • 1
  • 9