pass variable value by popToViewController in swift

1.9k Views Asked by At

I have a variable "NameofCircle" on LocationVC ViewController and i have variable CName on this Controller i want to pass the CName value to LocationVC Controller by popToViewController. I tried below code but did not get the result.

let viewControllers = self.navigationController!.viewControllers
    for aViewController in viewControllers
    {
        if aViewController is LocationVC
        {
           let Location = LocationVC()
            Location.NameofCircle = CName
    _ = self.navigationController?.popToViewController(aViewController, animated: true)
            }
}
3

There are 3 best solutions below

13
RajeshKumar R On BEST ANSWER

Try this.

let viewControllers = self.navigationController!.viewControllers
  for var aViewController in viewControllers
  {
  if aViewController is LocationVC
     {
        let aVC = aViewController as! LocationVC
        aVC.NameofCircle = CName
        _ = self.navigationController?.popToViewController(aVC, animated: true)
     }
  }

another choice To pass value to Root ViewController

if let   myController  = self.navigationController?.viewControllers[0] as? LocationVC
  {
    myController.NameofCircle = CName
   _ =  self.navigationController?.popToViewController(myController, animated: true)
    }
1
Amna Farhan On

Just replace your line :

_ = self.navigationController?.popToViewController(aViewController, animated: true)

with this one:

_ = self.navigationController?.popToViewController(Location, animated: true)

0
Priyank Patel On

Swift 4,5

You can use with code.

 let viewControllers = self.navigationController!.viewControllers
            for aViewController in viewControllers
              {
              if aViewController is SelectDeviceToGroup
                 {
                    let selecteDevicesVc = aViewController as! SelectDeviceToGroup
                    selecteDevicesVc.isEditSelected = true
                    selecteDevicesVc.selectedDevices = self.selectedDevicesIds
                    _ = self.navigationController?.popToViewController(selecteDevicesVc, animated: true)
                 }
              }