对不起,如果标题有点模糊。我还在学习swift和segues,我有3个视图控制器,分别叫做EarthViewController
、MoonViewController
和JupiterViewController
。
以下是有效的部分:
EarthViewController -> MoonViewController
MoonViewController -> JupiterViewController
JupiterViewController -> MoonViewController,
and even JupiterViewController -> EarthViewController,
但是当我试图返回地球视图时,从
MoonViewController -> EarthViewController
开始的展开段不断抛出一个Thread 1: Signal SIGABRT
错误。以下是迄今为止的布局和代码:EarthViewController(视图控制器)
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let des = segue.destination as! MoonViewController
if (segue.identifier == "toMoonView")
{
print("Went to the moon")
}
}
@IBAction func backFromMoon(segue: UIStoryboardSegue){
if let scVC = segue.source as? MoonViewController
{
print ("Back from the Moon to Earth")
}
}
@IBAction func backFromJupiterToEarth(segue: UIStoryboardSegue){
if let scVC = segue.source as? JupiterViewController
{
print ("Back from Jupiter to Earth")
}
}
}
月光控制器
import UIKit
class MoonViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//------------------------------------------------------------------------
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let des = segue.destination as! JupiterViewController //<- ERROR HERE
if (segue.identifier == "toJupiterView")
{
print("Went to Jupiter")
}
}
//-----------------------------------------------------------------------
@IBAction func backFromJupiter(segue: UIStoryboardSegue){
if let scVC = segue.source as? JupiterViewController
{
print ("Back from Jupiter to the Moon")
}
}
}
JupiterViewController(尚未添加任何内容)
import UIKit
class JupiterViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
非常感谢您的帮助!谢谢您!
最佳答案
此函数在MoonViewController
中:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let des = segue.destination as! JupiterViewController //<- ERROR HERE
if (segue.identifier == "toJupiterView")
{
print("Went to Jupiter")
}
}
称为规则分段和展开分段。当您开始
JupiterViewController
时,segue.destination
确实是JupiterViewController
类型。但当您展开到ViewController
时,segue.destination
属于ViewController
类型。在第二种情况下,force cast
as! JupiterViewController
由于类型错误而崩溃。解决这个问题的一种方法是,当您确定了目的地后,将
des
的声明移到if
中:override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toJupiterView"
{
let des = segue.destination as! JupiterViewController
print("Went to Jupiter")
}
}