Delegate using Container View in Swift

I am developing an application for iPad Pro. In this application, use containerView 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 the View container.

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 does not receive anything in the setTouch function.

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

+7
uiviewcontroller swift swift2 uicontainerview
source share
2 answers

It looks like you have identified a delegate, but you have not identified a delegate. It happens to me all the time.

+4
source share

Like @nwales, you have not set a delegate yet. You should make a delegate to the prepareForSegue function on your first viewController (which contains the viewContainer)

First, select the inline segment and set the identifier in the attribute inspector. Then in parentViewController implements func prepareForSegue as follows:

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if(segue.identifier == "the identifier"){ let embedVC = segue.destinationViewController as! ContainerViewController embedVC.dataViewDelegate = self } } 
+17
source share

All Articles