Search code examples
functionmethodsswiftparent

initiate parent method from child view SWIFT


I'm looking for the best possible way to initiate a parent method from a child's view controller.

The parent is a scroll view with three UIViewController children nested inside. The code to have them initialized and attached works fine... just can't seem the find a way to call methods of parent.

thanks in advance!


Solution

  • A generic way to call (public/internal) methods in a parent from a child or another class entirely is to save a reference to the parent in the child

    class parent { 
        ...
    
        internal func doSomething() { 
            println("Did something...")
        }
    }
    
    class child {
        let pReference: parent
    
        init(p: parent) {
            self.pReference = p
        }
    
        internal func callInParent() {
            self.pReference.doSomething()
        }
    }
    
    let x = parent()
    let y = child(x)
    y.callInParent() // prints "Did something..."
    

    This is easy to practise inside a playground. Give it a go.