Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • I've setup a XIB for a view
  • I set the "Simulated Metrics" Size to iPhone 3.5-Inch
  • I've added auto-constraints to the subviews inside this view
  • In the View Controller I perform certain operations dependent on the subview (IBOutlet) frames/bounds in the viewDidLoad method
  • In the View I perform certain operations dependent on the subview (IBOutlet) frames/bounds in the awakeFromNib method

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)

like image 614
pkearney06 Avatar asked Apr 16 '15 12:04

pkearney06


People also ask

What is auto layout constraints in Swift?

Auto Layout constraints allow us to create views that dynamically adjust to different size classes and positions. The constraints will make sure that your views adjust to any size changes without having to manually update frames or positions.

When should I use layoutSubviews?

layoutSubviews() The system calls this method whenever it needs to recalculate the frames of views, so you should override it when you want to set frames and specify positioning and sizing. However, you should never call this explicitly when your view hierarchy requires a layout refresh.

How do constraints work in Xcode?

To create constraints select the button and click the Align icon in the auto layout menu. A popover menu will appear, check both “Horizontal in container” and “Vertically in container” options to center the button on the screen. Then click the “Add 2 Constraints” button. Run the application.


1 Answers

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.

like image 196
Michał Ciuba Avatar answered Oct 20 '22 00:10

Michał Ciuba