简体   繁体   English

ios swift 如何在导航栏中设置保存按钮

[英]ios swift how to set a save button in the navigation bar

I have a MainViewController which is a table view controller, with custom cells where the user can select some data.我有一个MainViewController ,它是一个表格视图控制器,带有自定义单元格,用户可以在其中选择一些数据。 There is a button on this MainViewController that goes to PreferencesViewController , which has two buttons on the navigation bar, one for back (it is wokring now good), and the other one for save (here is my problem)这个MainViewController上有一个按钮,可以转到PreferencesViewController ,导航栏上有两个按钮,一个用于返回(现在工作正常),另一个用于save (这是我的问题)

This is a screenshot of the navitation bar in the PreferencesViewController :这是PreferencesViewController导航栏的屏幕截图: 在此处输入图片说明

I drag a segue from the save bar button back to the MainViewController .我将一个 segue 从save栏按钮拖回MainViewController

my problem我的问题

when I hit save, the MainViewController appears, but without saving the values the the user has already selected.当我点击保存时, MainViewController出现,但没有保存用户已经选择的值。 sounds like a new instance of this MainViewContoller is being created.听起来像是正在创建此MainViewContoller的新实例。

What am i missing here?我在这里缺少什么? what other approach i should have already used please?我应该已经使用过哪些其他方法?

You need to connect your save button to an IBAction, not a segue.您需要将保存按钮连接到 IBAction,而不是 segue。

In that IBAction, do whatever you need to do to save your data, and then do a dismissViewController:animated: call yourself in code.在那个 IBAction 中,做任何你需要做的事情来保存你的数据,然后在代码中做一个dismissViewController:animated: 调用你自己。

If you wanted to use a segue you wouldn't be able to (easily) save your data, and yes, it creates a new instance.如果您想使用 segue,您将无法(轻松)保存您的数据,是的,它会创建一个新实例。

An alternative would be to connect your save button to an unwind segue, rolls back, or unwinds, one or more segues to get back to a previous view controller.另一种方法是将您的保存按钮连接到一个 unwind segue、回滚或展开一个或多个 segue 以返回到以前的视图控制器。 To do that you'd have to put your save logic in prepareForSegue (with code to test which segue is being invoked and only save in response to the save segue.)为此,您必须将保存逻辑放在 prepareForSegue 中(使用代码来测试正在调用哪个 segue 并且只保存以响应保存 segue。)

i found the solution myself using:我自己找到了解决方案:

1- custom delegate: 1-自定义委托:

2- self.navigationController?.popViewControllerAnimated(true) 2- self.navigationController?.popViewControllerAnimated(true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM