iosiphoneswiftconstraintsawakefromnib

Objective-C/Swift (iOS) When are the auto-constraints applied in the View/ViewController work flow?


I'm having some issues of figuring out when the auto-contraints setup on a XIB are applied in the view setup process.

For more explanation:

In those 2 methods (ViewController::viewDidLoad and View::awakeFromNib) the IBOutlet views HAVE been loaded but the constraints have no yet been applied. The actual frame is still set to the iPhone 3.5" size (width 320) when using a larger simulator (such as the iPhone 6 simulator).

When are these auto-constraints applied and when should any necessary operations that would need the ACTUAL frame/bounds of the subviews take place?

I'm using XCode 6.3, Swift (1.2)


Solution

  • The constraints are applied in the layoutSubviews method. So if you want to do something after they are applied in a UIView subclass, override the method:

       override func layoutSubviews() {
        super.layoutSubviews()
        //the frames have now their final values, after applying constraints
      }
    

    In a UIViewController subclass, use viewDidLayoutSubviews for the same purpose:

      override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        //the frames have now their final values, after applying constraints
      }
    

    Please note that you shouldn't set frame / bounds for a view if you added auto layout constraints to this view.