Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto Layout using initWithFrame?

Tags:

ios

autolayout

If I'm implementing AutoLayout programatically in iOS is it proper to use initWithFrame method? If not how to initialise a view of preferred size?

like image 637
Arock Avatar asked Jul 17 '13 12:07

Arock


People also ask

What are the different types of auto Layout?

There are three main types of Auto Layout issues: ambiguous layouts, unsatisfiable constraints and logic errors.

What is the use of auto Layout?

Auto Layout defines your user interface using a series of constraints. Constraints typically represent a relationship between two views. Auto Layout then calculates the size and location of each view based on these constraints. This produces layouts that dynamically respond to both internal and external changes.

What is auto Layout Xcode?

Auto layout will help keep the button central in different orientations and devices. It is a constraint-based layout system that allows developers to create an adaptive interface, that responds appropriately to changes in screen size and device orientation.

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.


1 Answers

Better to avoid initWithFrame unless you have no choice. With Auto Layout, the approach is to define two constraints that specify width and height. There's different ways to do this but if you're doing it programmatically, in the updateViewConstraints method of your view controller, or the updateConstraints method of the view, check if the constraints have already been created and if not, add them to your view.

E.g.

[myConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_mySubView]-(200)-|"
                                 options:0
                                 metrics:nil
                                 views:_myViewsDictionary]];

[myConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_mySubView(100)]-|"
                                 options:0
                                 metrics:nil
                                 views:_myViewsDictionary]];

That said, better to do it using Interface Builder. Once you get used to it - and it does take some getting used to - you'll find it a fantastic timesaver and much better than defining your constraints in code.

like image 198
Max MacLeod Avatar answered Sep 18 '22 10:09

Max MacLeod