2016-11-26 66 views
0

这里完成新手,并且我试图从tabelViewCell按下按钮时显示它的行号。Swift - 按下UIButton时不调用另一个类的函数

下面是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中插入了一个断点,并发现它从来没有被调用过。完成难倒。

在此先感谢。

+0

的可能的复制[iOS的Swift在表视图细胞按钮动作](http://stackoverflow.com/questions/28894765/ios-swift-button-action-in-table-view-cell) – DogCoffee

+0

你确定IBAction被调用吗? – TheValyreanGroup

+0

@TheValyreanGroup是的。在我从tableViewCell的原始代码中,它有'self.addButton.isEnabled = false',当按钮被按下时它变灰。 – qunayu

回答

-1

我的预感是你正在创建一个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以外的任何功能的类像你在原来的职位一样。

+0

出现错误:类型'UITableViewController'的值没有成员'addCellToHome' – qunayu

+0

将'as改为! UITableViewController'到'as! tableViewController',或者你的类名是什么。并且确保你将'instantiate'方法的'withIdentifier'部分改变为故事板中的VC ID。 – TheValyreanGroup

+0

@qunayu很高兴我能帮忙! – TheValyreanGroup

相关问题