Search code examples
swiftuiviewcontrolleruicontainerviewswift2

Delegate using Container View in Swift


I'm developing an app for iPad Pro. In this app, containerView use to add additional views and interact with them.

First, I created a protocol:

protocol DataViewDelegate {
    func setTouch(touch: Bool)
}

Then, I created my first view controller

enter image description here

import UIKit

class ViewController: UIViewController, DataViewDelegate {

    @IBOutlet var container: UIView!
    @IBOutlet var labelText: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func setTouch(touch: Bool) {
        if touch == true {
            labelText.text = "Touch!"
        }
    }

}

And finally, I created a view that will be embedded in containerView.

enter image description here

import UIKit

class ContainerViewController: UIViewController {

    var dataViewDelegate: DataViewDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func touchMe(sender: AnyObject) {
        dataViewDelegate?. setTouch(true)
    }

}

But for some reason, nothing happened, the first view controller receives nothing in setTouch function.

My question is: In this case, using container, how can I make the communication between two ViewsControllers?


Solution

  • Looks like you defined the delegate, but have not set the delegate. This happens to me all the time.