Search code examples
iosswiftuipageviewcontroller

Pass value from child view page to Pageview controller in swift


I am android developer and pretty new to iOS.

I have a pageView Controller say A. It is connected to three child View Controller. I want to get back a value from child View Controller back to Root Page View Controller. In android it can be easily done through interface passing and having trouble in doing in iOS with protocols.

I am doing like this

protocol Z { 
func runZ()
}


Class A: UIViewController, Z {


func runZ( withValue value: String)
{
//Perform some function
}


 var orderedViewControllers: [UIViewController] = {
    var myViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "myViewController") as! MyViewController
    myViewController.z  = self
    return [ myViewController,
             UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "C")]
}()
}


Class B : UIViewController{
var z = A.self
func sendBackToA(){
(z as! Z).runZ(withValue : "CustomString")
}

I get the error at myViewController.z = self as Cannot assign value of type '(A) -> () -> A' to type 'A.Type'.

I made it work somehow by initializing like this

myViewController.z = A.self

but my app is crashing

Could not cast value of type 'A.Type' (0x1e0d854d8) to 'Z'


Solution

  • protocol Z:class {
      func runZ(withValue value: String?)
    }
    
    
    class A: UIViewController, Z, UINavigationControllerDelegate {
    
    
    
    func runZ(withValue value: String?)
    {
    //Perform some function
    }
    
    
     var orderedViewControllers: [UIViewController] = {
        var myViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "B") as! B
        myViewController.z = self
        return [ myViewController,
                 UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "C")]
    }()
    }
       
    
    class B : UIViewController{
        weak var z:Z?
       func sendBackToA(){
        z?.runZ(withValue : "CustomString")
       }
    }