简体   繁体   中英

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 tabelViewCell 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.

I think you should either make a delegate protocol for the cell, something like MyCellDelegate .

See guide to delegates .

Or add an action to the cells button from cellForRow(at: IndexPath) in your tableViewController.

See guide to button actions

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM