qunayu qunayu - 11 days ago 7
iOS Question

Swift - Function from another class is not called when UIButton is pressed

Complete newbie here, and I'm trying to make a button from a tableViewCell display its row number when pressed.

Here's the code from tableViewCell:

var myTableViewController: tableViewController?

@IBOutlet var addButton: UIButton!


@IBAction func addButtonPressed(_ sender: Any) {
myTableViewController?.addCellToHome(self) //call add function
}


And from tableViewController:

func addCellToHome(_ cell: UITableViewCell) //specifies what is to be done when addButton is pressed
{

let row = tableView.indexPath(for: cell)

print(row as! String)
}


Can someone please tell me what I'm doing wrong? I inserted a breakpoint inside addCellToHome and turns out it's never called. Completed stumped.

Thanks in advance.

SOLVED

Changed the code from tableviewCell to

@IBAction func addButtonPressed(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myTableViewController = storyboard.instantiateViewController(withIdentifier :"identifier") as! tableViewController
myTableViewController.addCellToHome(self) //call add function
}

Answer

My hunch is you're creating a new instance of tableViewController instead of using the current one that is in memory. Try the following instead of creating a new instance of the VC.

@IBAction func addButtonPressed(_ sender: Any) { 
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let myTableViewController = storyboard.instantiateViewController(withIdentifier :"tableViewController") as! tableViewController
    myTableViewController?.addCellToHome(self) //call add function
}

If you plan on using this VC in other method calls, you can also initialize the the myTableViewController outside of any function in the class like you did in your original post.