I have tableView with button. When i click this button, my ViewController changes to the second one. Also i want to get some information from the first VC to the second one but here i get my problem, my variable doesn't change.
Related code:
class First_VC: UIViewController {
...
@IBAction func touch(_ sender: UIButton) {
if let indexPath = table.indexPath(for: sender.superview!.superview as! UITableViewCell) {
let cell = table.cellForRow(at: indexPath)
selectedName = cell?.textLabel?.text
performSegue(withIdentifier: "segue", sender: self)
// here it works fine, if i print (selectedName) it will work like expected
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.delegate = self
self.table.dataSource = self
names() { names in
self.heroNames = names
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "segue" else { return }
guard let vc2 = segue.destination as? Second_VC else { return }
vc2.name = selectedName ?? ""
// here i get nil when print (selectedName)
}
}
...
If you need any more info, feel free to ask. Trying to make an app with several ViewControllers the first time so maybe my mistake is a very silly one
Why not pass the selected name to prepare(for:sender:)
using the sender
parameter.
...
let selectedName = cell?.textLabel?.text
performSegue(withIdentifier: "segue", sender: selectedName)
and then read it as
let selectedName = sender as? String ?? ""
vc2.name = selectedName