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

匿名 (未验证) 提交于 2019-12-03 01:38:01

问题:

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)

回答1:

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.



回答2:

Note for Xcode 8: If you use auto layout, you may have a problem with new feature: view as [any device]. When you test your app on another device(simulator) and have inferred screen, screen bounds for this device gonna be applied in viewWillLayoutSubviews.



回答3:

you can use method

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

}

But this method will be called multiple times in a view's life cycle, such as orientation change or moving in and out views, so you need to handle this.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!