简体   繁体   English

Swift-按下UIButton时不会调用其他类的函数

[英]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. 在这里完成新手操作,我正在尝试使tabelViewCell中的按钮在按下时显示其行号。

Here's the code from tableViewCell: 这是tableViewCell的代码:

    var myTableViewController: tableViewController?

    @IBOutlet var addButton: UIButton!


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

And from tableViewController: 从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. 我在addCellToHome中插入了一个断点,结果它从未被调用过。 Completed stumped. 完成陷入困境。

Thanks in advance. 提前致谢。

I think you should either make a delegate protocol for the cell, something like MyCellDelegate . 我认为您应该为该单元格创建一个委托协议,例如MyCellDelegate

See guide to delegates . 请参阅代表指南

Or add an action to the cells button from cellForRow(at: IndexPath) in your tableViewController. 或从tableViewController中的cellForRow(at: IndexPath)将操作添加到单元格按钮。

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. 我的直觉是您正在创建tableViewController的新实例,而不是使用内存中的当前实例。 Try the following instead of creating a new instance of the VC. 请尝试以下操作,而不是创建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. 如果计划在其他方法调用中使用此VC,则也可以像在原始文章中所做的那样,在类中任何函数之外初始化myTableViewController

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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