识别UITableViewCell中的UIButton无法正常工作 - Swift

时间:2016-01-10 02:36:33

标签: ios swift uitableview

我试图通过在单元格内按下的按钮来识别单元格索引。完成此操作后,我试图将信息传递给另一个viewController

原帖可以在这里找到: detecting uibutton pressed in tableview: Swift Best Practices

我的代码目前看起来像这样:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let myCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! questionCell

    //indicates which button was pressed
    myCell.button.tag = indexPath.row
    myCell.button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

    return myCell
}

var selectedRow = Int()

//sets selected row variable to the row that was selected
func buttonClicked(sender:UIButton) {

    selectedRow = sender.tag
}

//sets the id of the question that was selected in the answers view controller
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

var destinationView: AFeedTableViewController = segue.destinationViewController as! AFeedTableViewController

    destinationView.currentQuestionId = idResults[selectedRow]
}

我的问题是在buttonClicked函数之前调用prepareForSegue函数,因此不会对我传递给另一个视图控制器的值进行更新。谁能解释如何解决这个问题? 感谢

编辑:单击按钮时,将执行segue

1 个答案:

答案 0 :(得分:1)

假设您的segue已连接到按钮,您不需要额外的目标。您可以通过prepareForSegue:sender:

中的发件人对象访问该按钮
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    guard let button = sender as? UIButton else { return }
    guard let destinationViewController = segue.destinationViewController as? AFeedTableViewController else { return }

    destinationViewController.currentQuestionId = idResults[button.tag]
}