【问题标题】:Swift 2 - prepareForSegue nil ValueSwift 2 - prepareForSegue nil 值
【发布时间】:2016-05-11 11:40:06
【问题描述】:

当我在UITableView 中选择一行时,我正在尝试通过另一个视图发送链接。 当我选择行时,我可以看到打印了链接,但是该值没有到达函数prepareForSegue。 似乎在UITableView 中的选择行之前调用了prepareForSegue 函数。

var videouserPath = ""

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        videouserPath =  self.arrayUserVideo[indexPath.row][4]
        print("tableview: ----\(videouserPath)")
    }


    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        print("segue: ----\(videouserPath)")
        if segue.identifier == "toUserVideo"

        {
            if let destinationVC = segue.destinationViewController as? GetVideo_ViewController{

                destinationVC.videoToDisplay = videouserPath
            }
        }
    }

我进入调试状态:

转场:----

tableview:----https://example.com/resources/1361929513_02-02-2016_125830.mov

为什么在选择之前调用segue函数?

【问题讨论】:

  • 也许通过在情节提要中设置从UIViewController 而不是从UITableViewCellGetVideo_ViewController 的segue?

标签: ios uitableview segue uistoryboardsegue


【解决方案1】:

当从故事板将UIStoryboardSegue 链接到UITableViewCell 时,消息的顺序是prepareForSeguedidSelectRowAtIndexPath

自动方法

完全绕过didSelectRowAtIndexPath

对于通用和单选单元格,您不需要实现didSelectRowAtIndexPath。让与UITAbleViewCell 关联的segue 完成工作,并像这样处理选择:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "detailSegueIdentifier" {
        if let indexPath = tableView.indexPathForSelectedRow {
            print(indexPath)
        }
    }
}

手动方法

如果您在 segue 之前绝对需要做额外的工作,请不要将其关联到 UITableViewCell,而是关联到 UITableViewController。然后,您需要以编程方式触发它。灵感here.
IB 中,将 segue 分配给 table view controller,给它一个标识符(比如detailSegueIdentifier),然后像这样调用它。

    override func tableView(tableView: UITableView,
                            didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("didSelectRowAtIndexPath")
        self.performSegueWithIdentifier("detailSegueIdentifier", sender: nil)
    }

将参数传递给segue:

调用 performSegueWithIdentifier 还可以让您有机会显式传递参数,而不是事后猜测 indexPathForSelectedRow,并且不依赖于全局 (*)。

override func tableView(tableView: UITableView,
                        didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("didSelectRowAtIndexPath")
    self.performSegueWithIdentifier("detailSegueIdentifier", sender: indexPath)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "detailSegueIdentifier" {
        if let indexPath = sender as? NSIndexPath {
            let name = db[indexPath.row].key
            if let controller = segue.destinationViewController as? DetailViewController {
                controller.name = name
            }
        }
    }
}

(*) 如果你能帮上忙,就不要依赖全局变量

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    相关资源
    最近更新 更多