Autolayout自动布局的使用

来源:互联网 发布:c语言编程心形图案 编辑:程序博客网 时间:2024/05/05 01:33

Problem:

you want to use auto layout programmatically.


Solution:

Apple的autolayout programming guide文档:

https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/Introduction/Introduction.html#//apple_ref/doc/uid/TP40010853

此外需要注意的是view controller执行autolayout的过程:

How View Controllers Participate in the View Layout Process

When the size of a view controller’s view changes, its subviews are repositioned to fit the new space available to them. The views in the controller’s view hierarchy perform most of this work themselves through the use of layout constraints and autoresizing masks. However, the view controller is also called at various points so that it can participate in the process. Here’s what happens:

  1. The view controller’s view is resized to the new size.

  2. If autolayout is not in use, the views are resized according to their autoresizing masks.

  3. The view controller’s viewWillLayoutSubviews method is called.

  4. The view’s layoutSubviews method is called. If autolayout is used to configure the view hierarchy, it updates the layout constraints by executing the following steps:

    1. The view controller’s updateViewConstraints method is called.

    2. The UIViewController class’s implementation of the updateViewConstraints method calls the view’s updateConstraints method.

    3. After the layout constraints are updated, a new layout is calculated and the views are repositioned.

  5. The view controller’s viewDidLayoutSubviews method is called.

Ideally, the views themselves perform all of the necessary work to reposition themselves, without requiring the view controller to participate in the process at all. Often, you can configure the layout entirely within Interface Builder. However, if the view controller adds and removes views dynamically, a static layout in Interface Builder may not be possible. In this case, the view controller is a good place to control the process, because often the views themselves only have a limited picture of the other views in the scene. Here are the best approaches to this in your view controller:

  • Use layout constraints to automatically position the views (iOS 6 and later). You override updateViewConstraints to add any necessary layout constraints not already configured by the views. Your implementation of this method must call [super updateViewConstraints].

    For more information on layout constraints, see Auto Layout Guide.

  • Use a combination of autoresizing masks and code to manually position the views (iOS 5.x). You override layoutSubviews and use it to reposition any views whose positions cannot be set automatically through the use of resizing masks.

    For more information on the autoresizing properties of views and how they affect the view, see View Programming Guide for iOS.


Discussion:

Demo:


0 0