Home > Enterprise >  Swift transit from vc to another vc
Swift transit from vc to another vc

Time:01-31

ViewController has a label and a button for go to secondVC. And secondVC has a text field , label , button to write user-entered text in the text field on the label. When user press the back button of navigation bar, I want transit secondVC's label's text to ViewController's label's text. How can I do this ?

ViewController's code:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var nameLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func goVC2(_ sender: Any) {
        performSegue(withIdentifier: "toVC2", sender: nil)
    }
  
    
}

secondVC's code:

import UIKit

class secondVC: UIViewController {

    @IBOutlet weak var nameField: UITextField!
    @IBOutlet weak var resultLabel: UILabel!
   
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    

    @IBAction func saveClicked(_ sender: Any) {
        resultLabel.text = nameField.text
    }
    
}

I tried prepare for segue in ViewController and but it was error. And I searched on google for this but I couldn't find solution.

CodePudding user response:

Use protocol for pass data from second VC to first VC. you need to create your own delegate method and call on dismiss with pass data, check below code :----

ViewController's code:

import UIKit

class ViewController: UIViewController, Delegate {

    @IBOutlet weak var nameLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func save(str : String) {
        self.nameLabel.text = str
    }

    @IBAction func goVC2(_ sender: Any) {
       if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "secondVC") as? secondVC {
                               
           vc.delegate = self
           self.present(vc, animated: true, completion: nil)
         }
    }
  
    
}

secondVC's code:

import UIKit

protocol Delegate : AnyObject {
    func save(str : String)
}

class secondVC: UIViewController {

    @IBOutlet weak var nameField: UITextField!
    @IBOutlet weak var resultLabel: UILabel!
    weak var delegate : Delegate?
   
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    

    @IBAction func saveClicked(_ sender: Any) {

       if let del = self.delegate {
                
            let txt = nameField.text
            del.save(str: txt)
            self.dismiss(animated: true, completion: nil)
        }
        
    }
    
}

  • Related