Swift 切换到表和从表切换ViewController 使用自定义 Segue 的问题

Swift Switching To and FromTable ViewController Issue Using Custom Segue

我在使用自定义 segue 时遇到了 运行 问题。我有两个 tableviews,我试图从中来回切换。当我单击 tableview1 中的单元格时,它应该将我带到 tableview2。我在 tableview2 上有一个按钮连接到故事板的出口。从那里它应该带我回到 tableview1 但每当我按下按钮时,应用程序崩溃并出现 BAD_ACCESS 错误。

这是我的自定义转场 class:

class TableViewSegue: UIStoryboardSegue {

override func perform() {
    scale()
}

func scale () {
   let toViewcontroller = self.destination
    let fromViewcontroller = self.source
    let containerView = fromViewcontroller.view.superview
    let originalCenter = fromViewcontroller.view.center
    toViewcontroller.view.transform = CGAffineTransform(scaleX: 0.05, y: 0.05)
    toViewcontroller.view.center = originalCenter

    containerView?.addSubview(toViewcontroller.view)

    UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
    toViewcontroller.view.transform = CGAffineTransform.identity
    }, completion: { success in
    fromViewcontroller.present(toViewcontroller, animated: false, completion: nil) //The application crashes and highlights this line as the error.
    }) 
} 

}

我已经在我的 tableViewController1 中实现了这个方法:

    @IBAction func prepareForUnwind(segue: UIStoryboardSegue) {

}

不确定为什么 tableview2 没有关闭。

编辑:问题与需要导航控制器有关。

问题是每次执行 segue 时,您都是 presenting toViewcontroller。因此,应用程序呈现 table2 over table1,然后尝试 again 呈现 table1 over table2 展开.

修改您的自定义 segue 以检查 - 本质上 - 您要去的方向:

class TableViewSegue: UIStoryboardSegue {

    override func perform() {
        scale()
    }

    func scale () {
        let toViewcontroller = self.destination
        let fromViewcontroller = self.source
        let containerView = fromViewcontroller.view.superview
        let originalCenter = fromViewcontroller.view.center
        toViewcontroller.view.transform = CGAffineTransform(scaleX: 0.05, y: 0.05)
        toViewcontroller.view.center = originalCenter

        containerView?.addSubview(toViewcontroller.view)

        let fromP = fromViewcontroller.presentingViewController

        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
            toViewcontroller.view.transform = CGAffineTransform.identity
        }, completion: { success in

            // if nil, we are presenting a new VC
            if fromP == nil {
                fromViewcontroller.present(toViewcontroller, animated: false, completion: nil)
            } else {
                fromViewcontroller.dismiss(animated: false, completion: nil)
            }

        })
    }

}

注意:这是假设:

  1. 不是 试图 push/pop 在 UINavigationController 内......你需要添加一些其他检查来处理它。
  2. 你只是进入一个层次,也就是说,你不是展示,展示,展示等等,然后然后 试图放松。