Swift: Accessing a view controller’s methods

Recently in a Swift project I was using NSNotificationCenter in a bunch of places so that my custom UIView classes could end up calling methods in the ViewController class. After a while I started getting notification bloat and it became a little confusing managing all the posting and listening. It was a bit of a mess for my tightly-coupled views and view controller.

So this is how I can call methods and stuff in my ViewController from my custom UIViews.

let appDelegate  = UIApplication.sharedApplication().delegate as! AppDelegate
parentViewController = appDelegate.window!.rootViewController as! ViewController

It’s a LOT easier to do this than setting up all those notification and observers. I think you’ll agree (unless you have very loosely coupled logic) that this is a nice solution and it works for Swift. I wasn’t sure how to set it up outside of how I approached it in Objective-C.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.