ovvloa
Last Updated: February 25, 2016
·
835
· girobai

Between two views: how to delegate something

Picture

import UIKit
// ViewController.swift => view 1

@objc protocol ViewControllerDelegate {
    optional func dealWithButton()
}

class ViewController: UIViewController, ViewControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func goToView2(sender: AnyObject) {
        var payload = "mypayload"
        var vc2:ViewController2 = UIStoryboard(name: "Main", bundle: nil)
            .instantiateViewControllerWithIdentifier("vc2") as ViewController2
        vc2.payload = payload
        vc2.delegate = self
        presentViewController(vc2, animated: true, completion: completeHandler)
    }

    func completeHandler(){
        println("complete handler")
    }

    func dealWithButton(){
        println("delegated func")
    }

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

}
// ViewController2.swift => view 2
import UIKit

class ViewController2: UIViewController {

    var payload:String?
    var delegate:ViewControllerDelegate?

    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        label.text = payload
        delegate?.dealWithButton!()
    }

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

ref: http://stackoverflow.com/questions/11632043/use-of-delegates-to-communicate-between-view-controllers!