JOnney
JOnney

Reputation: 89

Use closure to pass data between two controllers

my problem looks so simple, but since I am a beginner, I have problem to understand the concept of the closure to pass data between two controllers

for example I have a static table view controllers that has one cell and a title inside it

class FirstView: UITableViewController {

@IBOutlet weak var titleLabel: UILabel!

and I have an another view controller that contain a button inside it

class SecondViewController: UIViewController {


@IBAction func pressChangeButton(_ sender: UIButton) {

}

and there is segue1 between these two controllers, with identifier "segue1"

I want a to a simple task, I want to add a boolean closure that it will be true if the change button is pressed. that is why I create a closure function the second view controller that has change button.

var change : ((Bool) -> Void)?

I just want, that the second view controllers tells the first one that change closure is now true (after pressing the change button) and the first view controllers simply change the title table inside it to whatever (I just want to see that how it can be done)

I don't know I have to use prepare sugue function? Could anyone help me to understand this concept?

Upvotes: 1

Views: 6510

Answers (2)

alanpaivaa
alanpaivaa

Reputation: 2089

A closure is basically a piece of code that you can run. In Swift a closure is a first class citizen as it can be passed around as parameters and return type of functions. That being said, you can pass or set a closure as you normally would for other objects.

As per Sh_Kan's answer, just set SecondViewController's closure in prepare(for segue:sender:), always paying extra attention to retain cycles. You might also want to take a look at delegate design pattern in order to exchange data and messages between your controllers.

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try

class FirstView: UITableViewController {

    @IBOutlet weak var titleLabel: UILabel!

    @IBAction func goToSecond(_ sender: UIButton) {

        self.performSegue(withIdentifier: "segue1", sender: nil)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "segue1" {
            let des = segue.destination as! SecondViewController
            des.change = { [weak self] (value) in
                print(value)
                self?.titleLabel.text = "SetValue"// set a value
            }
        }
    }

}
class SecondViewController: UIViewController {

    var change : ((Bool) -> Void)?

    @IBAction func pressChangeButton(_ sender: UIButton) {

        change?(true)
    }

}

Upvotes: 5

Related Questions