Cesare Cesare - 7 months ago 12
Swift Question

How do I refer to methods in AppDelegate.swift?

I have a view controller called "Home" and I want to call one of its methods, which is called

myFunction()
.

let home = Home() as! UIViewController
home.myFunction()


This doesn't seem to work. Why?

Answer

If Home is your rootViewController then you can call the animateStuff method from your AppDelegate methods by doing so:

if let viewController = self.window?.rootViewController? as? Home {
    viewController.animateStuff()
}

If Home is not your rootViewContoller, then you have to check if presentedView controller is Home then call its methods:

if let viewController = self.window?.rootViewController.presentedViewController as? Home {
    viewController.animateStuff()
}

And finally it looks like that your animateStuff method should first set buttons transform to its initial state

func animateStuff(){
    let optionsAnimateStuff = UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse | UIViewAnimationOptions.AllowUserInteraction
    self.buttonPlay.transform = CGAffineTransformMakeScale(1.0, 1.0)
    UIView.animateWithDuration(1.0, delay: 3.0, options:
        optionsAnimateStuff, animations: {
            self.buttonPlay.transform = CGAffineTransformMakeScale(1.13, 1.13)
        }, completion: { finished in
    })
}