Swift准备Segue:如何知道如果一个按钮或表行发起了Segue

时间:2017-06-23 17:28:25

标签: ios swift segue

这是我的代码。我正在尝试执行一个赛格。我有一个条形按钮项目以及一个表格执行相同segue的表格。我想知道点击按钮的时间以及特定行的时间。

以下代码适用于按钮,但不适用于表格的行

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    activePlaceRow = indexPath.row

    performSegue(withIdentifier: "toMap", sender: nil)

}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "toMap"
    {
        let mapViewController = segue.destination as! ViewController

        if let senderObject = sender
        {
            if (senderObject as! UIBarButtonItem).tag == 1
            {

                mapViewController.activePlaceRow = -2
            }
            else
            {
                mapViewController.activePlaceRow = activePlaceRow
            }
        }

    }
}

3 个答案:

答案 0 :(得分:2)

只需将索引路径传递为sender

即可
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    performSegue(withIdentifier: "toMap", sender: indexPath)

}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "toMap"
    {
        let mapViewController = segue.destination as! ViewController

        if let buttonItem = sender as? UIBarButtonItem, buttomItem.tag == 1 {
            mapViewController.activePlaceRow = -2
        }
        else if let indexPath = sender as? IndexPath {
            mapViewController.activePlaceRow = indexPath.row
        }
    }
}

答案 1 :(得分:0)

您可以为UIViewController

添加属性

var isSegueFromCell:Bool = false

didSelectRowAt方法中,您可以将此值指定为true。然后,当您调用prepareForSegue方法时,请检查:

if isSegueFromCell {

    print("SEGUE FROM TABLE VIEW")
}
else {
    print("SEGUE FROM BUTTON")
}

当您致电performSegue时,如果您使用Bool方法调用<{1}},则可以传递true didSelectRow

performSegue(withIdentifier: "YourSegueID", sender: true)

然后在prepareForSegue方法

中检测到这一点
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let value = sender as? Bool {
        if value {
            print("FROM TABLE VIEW ROW")
        } else {
            print("FROM BUTTON")
        }
    }
}

答案 2 :(得分:0)

一件容易的事就是检查indexPathForSelectedRowindexPathsForSelectedRows

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

if segue.identifier == "toMap"
{
    let mapViewController = segue.destination as! ViewController

    if let senderObject = sender
    {
        if (senderObject as! UIBarButtonItem).tag == 1
        {

            mapViewController.activePlaceRow = -2
        }
        else
        {
            mapViewController.activePlaceRow = tableView.indexPathForSelectedRow
        }
    }

}

这种方式无需activePlaceRow。您还可以通过右键单击单元格并拖动到视图控制器,在故事板中创建segue,然后删除didSelectRow实现。