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?
There are three main types of Auto Layout issues: ambiguous layouts, unsatisfiable constraints and logic errors.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With