Automatic Layout AutoLayout Usage summary (source with Swift version)

Source: Internet
Author: User


I. Overview


The use of AutoLayout has been around for some time, objective-c and Swift, under IOS7 and IOS8,



All the way to meet a lot of pits, with the fill, to today is also a lot of accumulated experience, here to summarize,



Share it with your new Doubi demo. Doubi Demo I've uploaded to GitHub



Go (address is: https://github.com/lihux/iLihuxAutoLayout), after each article of the demo are



will be placed in on GitHub, for your reference. There are two projects in the workspace of the source code, using OC and Swift respectively .



To achieve the same function, everyone learns AutoLayout and can learn by comparing the two languages.



, experience the difference between OC and swift programming, and then try to implement it in two languages at the same time.



In learning English, the teacher will tell us that the real proficiency in the use of English logo is you



Naturally not only speak in 中文版 but think in 中文版, that is, to learn to think in English, and



Not only will the mother tongue think after the sentence in the brain after the translation in English to speak out, can really do this



Point, just calculate the real master of English. In the same way, to truly master AutoLayout, you must forget



Frame, learn to use AutoLayout language to think and practice. Specifically, when creating the UI,



Use AutoLayout in storyboard or code to build the UI instead of directly modifying the frame;



, the same is done by modifying the AutoLayout to achieve the animation effect.



In general, the use of automatic layout (AutoLayout) is divided into two steps: The first is to create a AutoLayout,



This step, mainly through the combination of code and storyboard Way, through the UI space (UIView,



UIbutton) add constraints (constraint), let the UI meet the static design needs of our products; Second



is based on user interaction to modify or delete existing constraints on the UI to produce a corresponding animation effect.



Constraints Additions and deletions can be added by storyboard and code add two ways, the former advantage is



can be very intuitive to add constraints quickly, 80%-90% of the constraints can be done in this way fast, Real



The efficiency of this method is no less than that of the previous frame+autoresizingmask, and the advantages of the latter



is dynamic, flexible, and can create new constraints at run time to meet the needs of a particular environment, while repairing



change, delete existing constraints, usually only through the code to achieve. In general, there will be a 10%~20% Scenario



The code is used to add the constraint. These two ways are complementary, to use the automatic layout for their own



Work, both methods must be mastered at the same time.


two. Detailed


The following is an actual Doubi demo to show the general process of an automatic layout, which includes:



1) in create constraints in storyboard;



2) by modifying the constraints to achieve a simple animation;



3) The specific scene must be added by manual code constraints;



The demo is divided into two scenarios, as shown in the scenario:






Scenario 1: Adding Constraints to the main display storyboard and animating effects with constraints









Scenario 2: Scenarios where you must add constraints using code





1) Create a constraint in storyboard


in my previous blog post, I've talked about how to create a constraint in SB No more here, just simple



List the constraints I added, as shown in:






There are two points that need to be mentioned here to create a constraint: One, we introduced an auxiliary view, as I



As mentioned in the previous article, this is also one of the most common techniques used in automatic layout. Through the introduction of a anchor view,



We are able to skillfully convert the layout work relative to the whole to the local (anchor view) cloth



work, to some extent, reduce the workload and the complexity of the layout. So that it happens to be in the center of the entire view



(Horizontal center + vertical center) as our "anchor point", then all other view (direct or indirect



Use this auxiliary view as a reference to add constraints so that you can ensure that the entire UI is on a horizontal screen or a small screen,



There is also a good display on the phone.






Horizontal screen effect



The second is that we apply the leading and trailing to the Doubi at the same time in the horizontal direction, about two mutually exclusive



This is mainly used for the implementation of the back animation, in order to allow the two conflicting constraints to exist properly, I



they must to lower the priority of one of the constraints (the default priority is 1000, here we turn down to



actually is as good as 1000 must not).


2) Simple animations by modifying constraints


We have added two mutually exclusive constraints for Doubi, which is intended to achieve a click of about two



button, Doubi can swipe left and right: Modify the Doubi constraint and call UIView's animation



Block implementation animation.



To modify the Doubi body constraint (constraint) First is to be able to obtain and modify the action on Doubi



On the constraint, one of my previous posts talked about a method by traversing the constraints on its superview



The array is determined by the constraint attribute to find the constraint (and the constraint between the parent view is placed only in the parent view



In the constraints attribute instead of your own constraints attribute). In fact, Doubi demo uses a



A better approach: the constraints in storyboard are introduced directly into the code by means of Iboutlet:






Use Iboutlet to directly drag constraints directly from the storyboard into the code



When we need to be aware of this, we use the strong property to modify the printed constraints, which prevents



constraints are not used while still maintaining a strong application without being released , strong references in OC are used strong key



The word, while in swift it is strong without weak modification.



The following is the OC version of the animation code:




- (void)animatedMoveDoubiIsLeft:(BOOL)isLeft
{
    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1) { //ios8
        self.kidLeftCenterConstraint.active = isLeft;
        self.kidRightCenterConstraint.active = !isLeft;
        [UIView animateWithDuration:kAnimationDuration animations:^{
            [self.view layoutIfNeeded];
        }];
    } else { //ios7
        NSLayoutConstraint *constraintToRemove = !isLeft ? self.kidLeftCenterConstraint : self.kidRightCenterConstraint;
        NSLayoutConstraint *constriaintToUse = isLeft ? self.kidLeftCenterConstraint : self.kidRightCenterConstraint;
        [self.douBi.superview removeConstraint:constraintToRemove];
        [self.douBi.superview removeConstraint:constriaintToUse];
        [self.douBi.superview addConstraint:constriaintToUse];
        [UIView animateWithDuration:kAnimationDuration animations:^{
            [self.view layoutIfNeeded];
        }];
    }
}

In Swift, it is Jiangzi:






  func animatedMoveDoubi(isLeft: Bool)
    {
        if NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1 {
            self.kidLeftCenterConstrait.active = isLeft
            self.kidRightCenterConstrait.active = !isLeft
            UIView.animateWithDuration(kAnimationDuration, animations: { () -> Void in
                self.view.layoutIfNeeded()
            })
        } else {
            let constraintToRemove = isLeft ? self.kidRightCenterConstrait : self.kidLeftCenterConstrait
            let constriaintToUse = isLeft ? self.kidLeftCenterConstrait : self.kidRightCenterConstrait
            self.douBi.superview!.removeConstraint(constraintToRemove)
            self.douBi.superview!.removeConstraint(constriaintToUse)
            self.douBi.superview!.addConstraint(constriaintToUse)
            UIView.animateWithDuration(kAnimationDuration, animations: { () -> Void in
                self.view.layoutIfNeeded()
            })
        }
    }

It is necessary to note that active in constraint is used to identify the current constraint in its view using the





When the layout is applied, similar to the Enable property in UIButton, but this property is only in the latest



IOS8, this property cannot be used if the app is to support iOS7 devices, but only



Implemented by deleting related constraints. Some children's shoes brainwave may say, "Yes, we can change those two.



The precedence of a mutually exclusive constraint to implement an animation by selecting one of the constraints. The reality is: No!



Once a constraint is set up, you can change very little: generally only consant and active properties,



Other properties cannot be modified once they are added to the view, otherwise there will be unknown consequences for the program. Recommended Use



AutoLayout's children's shoes take a good look at the NSLayoutConstraint.h file and its reference documentation to find out



What are the role of member variables and methods in constraint?


3) Use code to add constraints in specific scenarios


In Doubi demo Scenario 2, we created a tableview that ran three cells,



The user clicks on the delete icon on the cell to remove the cell, and when the cell is deleted, we want to TableView



Show a view with an empty hint, which is quite common in apps that need to be networked in general: when



When the network is disconnected, data cannot be obtained and a view is displayed to show the user that there is no network. This is usually done by



Set TableView background view to implement, we put a UIView set the prompt icon, and then



Assign it to the Backgroundview property of TableView, and then the callback method that returns the number of cells



If the number of cells is 0, empty view is displayed, otherwise hidden.



In the implementation, we now storyboard this empty view layout, introduced through the Iboutlet



In the code, it is assigned to the Backgroundview property of TableView in the Viewdidload method,



Note that the empty view can be assigned to Tableview.backgroundview directly on the iOS8, Empty



It's no problem to add a constraint between view and its superview, or no more constraints, but in IOS7 you do not



line: If the empty view is directly assigned to the past, no matter how the add constraint will be dashed! Apple is really



The pits are endless. ! The workaround is to create an empty view that does not initialize any constraints and frame information as



Empty view's parent view, assign the view to Background view, set up the empty view and the



Container the constraint relationship between the view, the code looks like this:



Objective-c version:

- (void)customUI

{

   UIView *backgroundView = [UIView new];

   [backgroundView addSubview:self.emptyView];

   NSDictionary *views = @{@"backgroundView": self.emptyView};

   [backgroundView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[backgroundView]|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:views]];

   [backgroundView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[backgroundView]|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:views]];

   self.tableView.backgroundView = backgroundView;

}






Swift version:

func customUI()

   {

       let backgroundView = UIView()

       backgroundView.addSubview(self.emptyView)

       let views = ["backgroundView": self.emptyView]

       self.emptyView.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[backgroundView]|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: views))

       self.emptyView.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[backgroundView]|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: views))


       self.tableView.backgroundView = backgroundView

   }






In the code we use the Apple's VFL language implementation constraints, in fact code creation constraints can also be





Nslayoutconstraint's ConstraintWithItem:relatedBy:toItem:attribute:multipler:constant



method implementation, the latter is slightly troublesome, but if you want to establish a scaling factor is not 1 (multipler!). =1) constraints



Can only be achieved by this method, the VFL language cannot modify the scaling factor, in addition to using the VFL method to create



Out is an array of constraints, while the latter creates a separate constraint object that, for these details,



everyone in the heart to have a few. the VFL language format although I look a bit strange, but actually compared image, Jane



single, if you seriously get See, it's pretty cool to use, adding a constraint in minutes is not what to ask .



questions. Study the VFL language I would like to recommend a foreigner to write a blog post (but it seems to be a wall, OK,



The time I give translation, in addition to look at the official Apple documents, this article is enough. ):



http://commandshift.co.uk/blog/2013/01/31/visual-format-language-for-autolayout/


Iii. Summary


This paper mainly from a relatively coarse range, relying on a small doubi Demo, a summary of the introduction of



the use of AutoLayout and some of the techniques and pit pits. Details are no longer detailed, a random search, online



a bunch, I no more wheels to be made again. the use of automatic layouts in projects that use storyboard, 80%



the above work is in the storyboard Easy to complete (if your project has not yet been used storyboard



(story version), then all right, AutoLayout. It's a bit hard to use: you're going to have a big, big segment.



code to write, even if it is written in the VFL language, its readability is far less readable in storyboard



intuitive and convenient). There are some parts of the code that must be implemented, such as implementing animations by modifying constraints and a



Some special scenarios where you can add constraints manually. Read other people's text, such as their own practice, and now began to write their own



Layout code bar, only practice is the best way to learn!



Finally, summarize and list some experience in the process of AutoLayout use:



1. Be sure to use storyboard skillfully and master how to add constraints in storyboard, as this



It takes up more than 80% of the layout (what?). Storyboard, you're not going to use it? So hurry to learn, don't tell me pure code to write the program is called NB, the reality is, the current technical maturity and product development efficiency requirements are required you quickly use up storyboard, and the pure code in the write constraints is a time-consuming effort is not pleasing things, hundred cent of the chicken;



2. The implementation of the animation, you can use Iboutlet to easily modify the constraints created in SB to achieve animation;



3. Learn to use the VFL language, which is a tool for your code to implement constraint!



Automatic Layout AutoLayout Usage summary (source with Swift version)




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.