Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Introduction to Auto Layout in iOS Visual Format Language Complex Format Strings

landon vago-hughes
landon vago-hughes
6,392 Points

Where to apply the layout code in xcode

I was wondering if all the code necessary to programmatically change the layout of my views has to be under viewDidLoad() or whether I could just create new swift file to contain all my layout code? This is one of the more annoying things i seem to find rather challenging is where to start implementing my code. So my query really is when im working on an app, to make it alot less clumpy would it be better to have all the layout code in another folder in some function that i could then call under viewDidLoad() or is there no point?

Oliver Duncan
Oliver Duncan
16,642 Points

Haven't taken this course yet, but I imagine building a library with useful layout functions would be a great way to organize your code.

1 Answer

Anthony Boutinov
Anthony Boutinov
13,844 Points

You can store all this code in another Swift file, but the call to that code must be initiated from viewDidLoad().

Something like

LayoutManager.swift

class LayoutManager {
   // ...
   func layoutElements(onView view: UIView) {
      // layout code
   } 
}

ViewController.swift

...
let layoutManager = LayoutManager()

func viewDidLoad() {
   //...
   layoutManager.layoutElements(onView: self.view)
}
...

There are many design patterns, and several of them may be used in here. This one is called Delegation.

Anthony Boutinov
Anthony Boutinov
13,844 Points

Google Design patterns. There are some courses on them in Treehouse too.