繁体   English   中英

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

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

在这里完成新手操作,我正在尝试使tabelViewCell中的按钮在按下时显示其行号。

这是tableViewCell的代码:

    var myTableViewController: tableViewController?

    @IBOutlet var addButton: UIButton!


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

从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)
}

有人可以告诉我我在做什么错吗? 我在addCellToHome中插入了一个断点,结果它从未被调用过。 完成陷入困境。

提前致谢。

我认为您应该为该单元格创建一个委托协议,例如MyCellDelegate

请参阅代表指南

或从tableViewController中的cellForRow(at: IndexPath)将操作添加到单元格按钮。

请参阅按钮操作指南

我的直觉是您正在创建tableViewController的新实例,而不是使用内存中的当前实例。 请尝试以下操作,而不是创建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
}

如果计划在其他方法调用中使用此VC,则也可以像在原始文章中所做的那样,在类中任何函数之外初始化myTableViewController

暂无
暂无

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

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