简体   繁体   English

在iOS Swift中的视图之间的模型之间保存数据

[英]Save data in Model between Views in iOS Swift

I'm very new in iOS development and I'm stuck on how to save data into the model when accessing several views.. 我在iOS开发中是一个新手,在访问多个视图时,我坚持如何将数据保存到模型中。

I have a pizza selector (for the sake of this example I'm going to simplify the model), my root file have 2 buttons label as: "Size","Dough", each time you press a button you navigate to a new ViewController within a show segue, in here you have a picker to select from 3 types of sizes or doughs. 我有一个披萨选择器(为了简化本示例,我将简化模型),我的根文件有2个按钮标签,分别为:“大小”,“面团”,每按一次按钮,您都导航到一个新的展示区中的ViewController,在这里有一个选择器,可以从3种尺寸或面团类型中进行选择。

What I'm not capable of doing is to save the data from one of the views when returning from the other, I mean, if you press the size button and select for example "large" when you clic on accept it returns to the ViewController class and I have the value of "large" but now if you press on the "Dough" button and select "thin" when you come back it only have the "thin" value the previous size values is lost... 我无能为力的是从另一个视图返回时保存其中一个视图的数据,我的意思是,如果您按大小按钮并在选择接受时选择例如“大”,则返回到ViewController班级,我的值是“大”,但是现在,如果您按“面团”按钮并选择“薄”,当您回来时,它只有“薄”值,以前的尺寸值会丢失...

This is the ViewController (root file): 这是ViewController(根文件):

class ViewController: UIViewController {

    let pizza = Pizza(tamano: "", masa: "")

    enum Constantes {
        case Tamano
        case Masa
    }

    @IBOutlet weak var tamanoLabel: UIButton!
    // Almacenamos el tamaño de la pizza
    var tamanoPvara:String?
    var tipoMasa:String?

    // Almacenamos cuales tipos/ingredientes aun no tengo
    var compruebaEleccion = [Constantes.Tamano:false]


    override func viewDidLoad() {
        super.viewDidLoad()
        print("tamano: \(pizza.tamano) masa: \(pizza.masa)")
        // Do any additional setup after loading the view, typically from a nib.
        //        if let (pizza.model["Tamano"] != "") {
        //            labelTamanoPizza.text = pizza.model["Tamano"]
        //        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func btnConfirmacion(sender: AnyObject) {
        // Variable para saber si estan todos los pasos hechos
        print("tamano: \(pizza.tamano) masa: \(pizza.masa)")

    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "tamanoPizza") {
            print("tamaño")
            let destinationViewController = segue.destinationViewController as! ViewTamanoController
            destinationViewController.pizza = self.pizza
        }
        if (segue.identifier == "TipoMasa") {
            print("masa")
            let destinationViewController = segue.destinationViewController as! ViewTipoMasaController
            destinationViewController.pizza = self.pizza
        }
    }


}

This is the ViewSizeController: 这是ViewSizeController:

class ViewTamanoController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {


    @IBOutlet weak var tamanoSelector: UIPickerView!
    @IBOutlet weak var labelTamano: UILabel!

    let pickerData = ["Chica","Mediana","Grande"]

    var pizza = Pizza?()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        tamanoSelector.dataSource = self
        tamanoSelector.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickerData[row]
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        labelTamano.text = pickerData[row]
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "fromTamanoToController") {
            print("segue tamaño")
            let viewController = segue.destinationViewController as! ViewController
//            viewController.tamanoPizza = labelTamano.text;
            viewController.pizza.tamano = labelTamano.text
        }
    }

    @IBAction func btnAceptar(sender: AnyObject) {
//        print("aceptar tamaño")

        pizza!.tamano = labelTamano.text
         print(pizza!.tamano)
    }
}

And this is the ViewDoughController 这是ViewDoughController

class ViewTipoMasaController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate  {

    @IBOutlet weak var tipoMasaLabel: UILabel!
    @IBOutlet weak var tipoMasaSelector: UIPickerView!

    let pickerData = ["Delgada","Crujiente","Gruesa"]

    var pizza = Pizza?()


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        tipoMasaSelector.dataSource = self
        tipoMasaSelector.delegate = self

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickerData[row]
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        tipoMasaLabel.text = pickerData[row]
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "fromTipoMasaToController") {
            let viewController = segue.destinationViewController as! ViewController
//            viewController.tipoMasa = tipoMasaLabel.text;
            viewController.pizza.masa = tipoMasaLabel.text
        }
    }

    @IBAction func btnAceptar(sender: AnyObject) {

        pizza?.masa = tipoMasaLabel.text
        print(pizza!.masa)
    }

}

I know this is kind of easy question but any help will be appreciated 我知道这是一个简单的问题,但会有所帮助

Thank you so much 非常感谢

I think I found your problem. 我想我找到了你的问题。 In the details ViewControllers you are performing a new segue, which means you are creating each time a new parent ViewController. 在详细信息ViewController中,您正在执行一个新的Segue,这意味着您每次创建一个新的父ViewController。 What you have to do is to dismiss the detail View Controller. 您要做的是关闭细节视图控制器。 You don't need the methods prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) in the Details ViewControllers. 您不需要Details ViewControllers中的prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)

Your btnAceptar function would be like that: 您的btnAceptar函数将如下所示:

@IBAction func btnAceptar(sender: AnyObject) {

        pizza?.masa = tipoMasaLabel.text
        print(pizza!.masa)
        self.dismissViewControllerAnimated(true, completion: nil)
    }

With dismissViewController you are actually returning to the first parent View Controller, and not the new one. 使用dismissViewController,您实际上将返回到第一个父级View Controller,而不是新的父级。

Now, you have to pass the parent ViewController the values for the dough and the size, and you can not do it so easy as you tried. 现在,您必须将其面团和大小的值传递给父级ViewController,您无法像尝试的那样轻松地完成它。 You have to ways of doing that: Notifications or Delegates. 您必须做到这一点:通知或代理。 You have here an easy example: Pass data when dismiss modal viewController in swift 这里有一个简单的示例: 快速关闭模式视图控制器时传递数据

Instead of the method "backFromCamera" you will have to make a prococol with the methods "setDough" and "setSize" for example. 例如,必须使用方法“ setDough”和“ setSize”来创建协议,而不是方法“ backFromCamera”。

Have fun ;) 玩得开心 ;)

the reason is because the root view controller is reloading new instance of let pizza = Pizza(tamano: "", masa: "") every time it loads. 原因是因为根视图控制器每次加载时都会重新加载let pizza = Pizza(tamano:“”,masa:“”)的新实例。

take the line let pizza = Pizza(tamano: "", masa: "") out of root view controller or get it from class instance. 将这一行从根视图控制器中移出Pizza = Pizza(tamano:“”,masa:“”)或从类实例中获取。

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

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