更新时间:2022-11-24 15:46:05
所以我想通了,主要来自这篇文章 - http://makeapppie.com/2014/09/15/swift-swift-programmatic-navigation-view-controllers-in-swift/
So I figured it out, based mostly from this post – http://makeapppie.com/2014/09/15/swift-swift-programmatic-navigation-view-controllers-in-swift/
在 SecondViewController
中,在类声明上方,添加以下代码:
In SecondViewController
, above the class declaration, add this code:
protocol SecondVCDelegate {
func didFinishSecondVC(controller: SecondViewController)
}
然后在SecondViewContoller
里面添加一个类变量:
Then inside of SecondViewContoller
add a class variable:
var 委托:MeditationVCDelegate!= 无
然后在按钮所针对的函数内部,添加以下内容:
Then inside of your function that your button targets, add this:
self.navigationController?.popViewControllerAnimated(true)
delegate.didFinishSecondVC(self)
我们在这里所做的是在 SecondViewController
中弹出,并且不传递任何数据,但是由于我们已经定义了一个协议,我们将在 ViewController
中使用它来处理数据.
What we're doing here is doing the pop in SecondViewController
, and not passing any data, but since we've defined a protocol, we're going to use that in ViewController
to handle the data.
接下来,在 ViewController
中,将您在 SecondViewController
中定义的协议添加到 ViewController
继承自的类列表中:
So next, in ViewController
, add the protocol you defined in SecondViewController
to the list of classes ViewController
inherits from:
class ViewController: UIViewController, SecondVCDelegate { ... your code... }
您需要添加我们在新协议中定义的函数,以使编译器满意.在 ViewController
的类中,添加:
You'll need to add the function we defined in the new protocol in order to make the compiler happy. Inside of ViewController
's class, add this:
func didFinishSecondVC(controller: SecondViewController) {
self.myBoolVar = true
controller.navigationController?.popViewControllerAnimated(true)
}
在我们调用 didFinishSecondVC
的 SecondViewController
中,我们在 ViewController
类中调用此方法,我们是控制器突然出现.这类似于我们在 SecondViewController
中编写此代码,但我们已将其编写在 ViewController
中,并且我们使用委托来管理两者之间的消息传递.
In SecondViewController
where we're calling didFinishSecondVC
, we're calling this method inside of the ViewController
class, the controller we're popping to. It's similar to if we wrote this code inside of SecondViewController
but we've written it inside of ViewController
and we're using a delegate to manage the messaging between the two.
最后,在ViewController
中,在我们要push到SecondViewController
的函数中,添加以下代码:
Finally, in ViewController
, in the function we're targeting to push to SecondViewController
, add this code:
let secondVC = secondViewController()
secondVC.delegate = self
self.navigationController?.pushViewController(secondVC, animated: true)
就是这样!你应该准备好在两个视图控制器之间传递代码而不使用故事板!
That's it! You should be all set to pass code between two view controllers without using storyboards!