Delegate using Container View in Swift

时光怂恿深爱的人放手 提交于 2019-12-20 12:35:50

问题


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

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.

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?


回答1:


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




回答2:


Like @nwales said you haven't yet set the delegate. You should do set the delegate in prepareForSegue function on your first viewController (who contain the viewContainer)

First select the embed segue and set an identifier in the attributes inspector. Then in the parentViewController implement the func prepareForSegue like this:

 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
    }
}


来源:https://stackoverflow.com/questions/34298760/delegate-using-container-view-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!