How to Pass information Back in iOS when reversing a Segue using Swift?

后端 未结 3 1599
滥情空心
滥情空心 2020-12-09 06:14

I have two view controllers, One and Two. I go from VC One to VC Two. On VC Two, I select some data that I store in an array. When I press the \"Back\" button on the navigat

3条回答
  •  温柔的废话
    2020-12-09 06:26

    Here is my solution in Swift 3

    1) Create a protocol inside the SecondController.swift file. We preferably create the protocol from where we will be getting data from.

    protocol Protocol {
            func passingDataBack(withString: String)
    }   
    

    2) Create a variable of type Protocol

    var proto: Protocol!
    

    3) Switch to the ViewController.swift file and inherit the Protocol we made from the SecondController.swift file.

    class ViewController: UIViewController, Protocol {
    
    }   
    

    4) We then want to conform to the Protocol we made by creating the function we made

        func passingDataBack(withString: String) {
    //        withString will return the value that has been passed from our SecondController class
            self.title = withString
    
        }
    

    5) Use the prepareForSegue method and segue to the SecondController class

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            let vc = segue.destination as? SecondController
            vc?.proto = self //This line will instantiate the protocol to our ViewController class
        }
    

    6) Go back to our SecondController.swift file and use the didSelectRow method and pass our data

     override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
        proto.passingDataBack(withString: items[indexPath.row]) //Call the protocol and the function then pass our data.
        _ = self.navigationController?.popViewController(animated: true) //This will pop back to our previous controller.
    
    }
    

    * Important Things To Remember!!! *

    You must set the protocol from controllerB to instantiate to controllerA when switching from controllerA to controllerB

    In our example, we moved from ViewController to SecondController. We instantiate our protocol from our SecondController by doing

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as? SecondController
        vc?.proto = self //This line will instantiate the protocol to our ViewController class
    }
    

    If you do not do this, you will get a Thread 001 error on this line

    proto.passingDataBack(withString: items[indexPath.row]) //Call the protocol and the function then pass our data.
    

    Source code Github

提交回复
热议问题