将数据传回前一个控制器
我在故事板中有两个控制器,嵌入在导航控制器中,并且有一个segue可以在它们之间切换。
通过实现prepareForSegue,将数据从第一个控制器传递到第二个控制器非常简单,并使用segue.destinationViewController 设置第二个控制器的属性。
我也应该将数据从第二个控制器传回前一个控制器。我用谷歌搜索,但没有找到任何简单但有效的代码来演示它。
您能否给我一个关于最佳方法的简单示例?
提前致谢!
I have two controllers in the storyboard, embedded in a NavigationController, and there is a segue to switch between these.
Passing data from the first controller to the second one is pretty straightforward by implementing prepareForSegue, and set the properties of the second controller using segue.destinationViewController.
I should pass back data to the from the second controller to the previous one also. I googled, but I have not found any simple, but working code to demonstrate it.
Would you be so kind give me a simple sample about the best way to do it?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在第二个视图控制器类中,您创建一个协议和委托。第一个视图控制器将自己设置为prepareForSegue中的委托并实现协议方法。然后,第二个视图控制器将调用方法将数据传递回第一个视图控制器。以下是我的一个项目中的一些代码作为示例。
In your second view controller class you create a protocol and delegate. The first view controller will set it self as the delegate in prepareForSegue and implement the protocol methods. The second view controller will then call the methods to pass data back to the first view controller. Here is some code from one of my projects as an example.
当您设置要传递给第二个控制器的数据时,您还可以设置指向前一个控制器的指针。
when you set the data you're passing to the second controller you can also set a pointer to the previous one.
“推荐”的方法是使用委托。在
-prepareForSegue:
调用期间将第一个视图控制器将自身设置为新视图控制器的委托,然后在完成后调用您定义的任何委托方法。这比紧密耦合两个控制器要多一些工作,但如果您发现需要以稍微不同的方式使用控制器,它实际上可以节省时间。如果您观看有关使用 IB 和 Storyboard 的 WWDC'11 视频,它们实际上会深入探讨此模式并包含代码示例和演示,因此我建议您看一下。
The "recommended" way of doing this is using a delegate. Have the first view controller set itself as the delegate of the new view controller during the
-prepareForSegue:
call, then when you're done, you call whatever delegate methods you've defined.This is a bit more work than tightly coupling the two controllers, but it actually saves time if you ever find you need to use the controller in a slightly different way. If you watch the WWDC'11 video on using IB and Storyboards, they actually go through this pattern in depth and include code examples and demos, so I recommend taking a look at that.
我一直在研究如何将数据从一个视图控制器传递到另一个视图控制器这个问题的所有变体,并且发现 Apple 的第二个 iOS 应用程序教程不仅有代码,而且对所涉及的所有内容都有可爱的解释。
I've been studying all of the variants to this question of how to pass data from one view controller to another and have come to see that Apple's Second iOS App Tutorial has not only the code but a lovely explanation of everything involved.