Search code examples
swiftuinavigationcontrollerdelegatessegueprotocols

How can I use a protocol in combination with a navigation controller?


Hey guys I have a little question again. How can I use a protocol in combination with a nav controller. So first of all here are my two classes:

First View Controller:

class VC1: UIViewController{

var cons = "nothing"

@IBAction func PRINT(_ sender: Any) {
    print(cons)
}

@IBAction func PRESENT(_ sender: Any) {
    let VC = storyboard?.instantiateViewController(identifier: "VC") as! VC2
    VC.delegate = self
    present(VC, animated: true, completion: nil)
}  }

extension VC1: data {
func give(text: String) {
    cons = text
} }

Second View Controller:

protocol data {
func give(text: String)}

class VC2: UIViewController {

var delegate: data!

@IBAction func SAVEDISMISS(_ sender: Any) {
    delegate.give(text: "Hallo")
    dismiss(animated: true, completion: nil)
}}

And here is also my storyboard: enter image description here

So now I will come to my problem. When I run the code there is an error message when I perform any segue on VC2 because by using the protocol, the navigation controller is excluded, but when i present the navigation controller instead of VC2 the protocol isn´t working anymore.

What could I change so that the navigation controller isn´t excluded and the protocol is working both.

Hopefully anyone can help me, and sorry for my bad english again. I hope you can understand everything.

Have a great day or night.


Solution

  • Replace PRESENT function with the following code when you are trying to present a UINavigationController.

    @IBAction func PRESENT(_ sender: Any) {
        let VC = storyboard?.instantiateViewController(identifier: "VC") as! VC2
        VC.delegate = self
        let navigationController = UINavigationController(rootViewController: VC)
        present(navigationController, animated: true, completion: nil)
    }