0

I am defining this in a UIViewController and trying to access myIndex in a different view controller. How can I do this?

I would like to do this programmatically without storyboards. Any help is much appreciated!

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //NSLog("You selected cell number: \(indexPath.row)!")
        let myIndex = indexPath.row
    }
Mike Perhats
  • 533
  • 1
  • 7
  • 11
  • The different view controller, if it's pushed or presented, then you can pass data from didSelectRow. Otherwise, use a sharedInstance to pass data between different controllers. – anuraagdjain Jul 17 '19 at 03:40
  • https://stackoverflow.com/questions/5210535/passing-data-between-view-controllers – k-thorat Jul 17 '19 at 03:43

2 Answers2

1

You have to consider passing Indexpath like this:

performSegue(withIdentifier: "NextView", sender: indexPath)

func prepareForSegue(segue: UIStoryboardSegue, sender: Any) {
    let indexPath = sender as! IndexPath
    let eventStruct =  post[indexPath.row]
    let secondViewController = segue.destination as? NextViewController
    secondViewController?.data = sender as AnyObject 
}
Nagarjun
  • 6,557
  • 5
  • 33
  • 51
0

If you want to access from anywhere of your project you can store the data in userdefault. inside your didSelectRowAt set the indexPath.row using key myIndex , this key should be unique:

UserDefaults.standard.set(indexPath.row, forKey: "myIndex")

Then retrieve the data from any viewController:

If UserDefaults.standard.object(forKey: "myIndex")!=nil{
    let savedIndexPath = UserDefaults.standard.integer(forKey: "myIndex")
}
SM Abu Taher Asif
  • 2,221
  • 1
  • 12
  • 14