【问题标题】:Xcode Segue "Could not cast value of type"Xcode Segue“无法转换类型的值”
【发布时间】:2017-07-01 02:18:23
【问题描述】:

我有两个不同的视图控制器,详细信息和搜索。转到 Detail 的 segues 工作正常,但转到 Search 的 segues 不断使应用程序崩溃。我花了两个小时阅读类似的问题,但似乎都没有相同的问题:

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

    let detailVC = segue.destination as! DetailViewController

    if segue.identifier == "newDocSegue"   {
        // Create a new document and pass it to the detail view.
        detailVC.doc = Document()
        detailVC.isAddAction = true
    }

    if segue.identifier == "editDocSegue"    {
        // Load the existing document into the detail view, for editing.
        let indexPath = tableView.indexPath(for: sender as! UITableViewCell)!
        detailVC.doc = Document[indexPath.row]
        detailVC.isAddAction = false
    }
     else if segue.identifier == "searchSegue" {
        shouldPerformSegue(withIdentifier: "searchSegue", sender: Any?.self)
    }

}

【问题讨论】:

  • segues 从 TableViewController 到 ViewControllers
  • shouldPerformSegue(withIdentifier: "searchSegue", sender: Any?.self),为什么会有这一行?
  • 您在第二个 if 语句中也缺少 else

标签: ios swift xcode


【解决方案1】:

您的问题出在:

let detailVC = segue.destination as! DetailViewController

如果你的目的地的类型是SearchViewController 会导致错误

试试这个:

if let detailVC = segue.destination as? DetailViewController

您应该了解as?as!

【讨论】:

  • 这是有道理的。谢谢。
【解决方案2】:

你的问题是

让 detailVC = segue.destination 为! DetailViewController

线。这将尝试将任何 VC(包括您的搜索 VC)转换为 DetailViewController。试试这个:

let detailVC : UIViewController

if segue.identifier == "newDocSegue"   {
    // Create a new document and pass it to the detail view.
    detailVC = segue.destination as! DetailViewController
    detailVC.doc = Document()
    detailVC.isAddAction = true
}

if segue.identifier == "editDocSegue"    {
    // Load the existing document into the detail view, for editing.
    detailVC = segue.destination as! ???  // not sure what type you want here
    let indexPath = tableView.indexPath(for: sender as! UITableViewCell)!
    detailVC.doc = Document[indexPath.row]
    detailVC.isAddAction = false
}
 else if segue.identifier == "searchSegue" {
    detailVC = segue.destination as! SearchViewController
    shouldPerformSegue(withIdentifier: "searchSegue", sender: Any?.self)
}

【讨论】:

  • 谢谢。这回答了它。我将 let 语句移到前两个 segue 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-26
  • 2018-11-02
  • 2016-03-05
  • 2023-03-20
  • 2015-11-16
相关资源
最近更新 更多