且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift - 使用popViewController并将数据传递给您要返回的ViewController

更新时间:2022-11-24 15:41:25

所以我想出来了,主要来自这篇文章 - 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 delegate:MeditationVCDelegate! = nil

然后在您的按钮所针对的函数内部添加:

Then inside of your function that your button targets, add this:

self.navigationController?.popViewControllerAnimated(true)
delegate.didFinishSecondVC(self)

我们在这里做的是在 SecondViewController 中执行pop,而传递任何数据,但是我们定义了一个协议,我们将在 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)
}

SecondViewController 我们正在调用 didFinishSecondVC ,我们正在调用这个方法在 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 中,在函数中我们是定位到推送 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!