Premiers pas avec la mise en page automatique
Installation ou configuration
Pour utiliser la mise en page automatique, nous devons activer un indicateur booléen dans le storyboard. Il est illustré dans l’image ci-dessous. Après cela, nous pouvons utiliser la mise en page automatique dans notre storyboard. Il existe une autre option si nous voulons utiliser des classes de taille ou non. La classe de taille est également une option utile dans la mise en page automatique qui nous aide à concevoir différemment pour différentes tailles d’écran d’appareils avec des éléments identiques ou différents. L’image de la configuration va ici. C’est à partir du panneau de l’inspecteur de fichiers de l’éditeur de propriétés dans Xcode.
[![entrez la description de l’image ici][1]][1]
[1] : http://i.stack.imgur.com/E5dM3.png
Ajout d’un UIImageView au centre de l’écran
Si vous souhaitez ajouter un UIImageView au centre de l’écran avec une largeur et une hauteur de 100 pixels, vous devez définir la contrainte centre x et la contrainte centre y sur la vue d’ensemble à partir de UIImageView et la contrainte largeur, hauteur sur UIIMageView. Voici le code. Il y a moyen de le faire dans le storyboard mais j’ai écrit dans le code car c’est compréhensible pour cette situation dans la documentation.
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100.0, 100.0);
imageView.self.translatesAutoresizingMaskIntoConstraints = NO;
[imageView addConstraint:[NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:100.0]];
[imageView addConstraint:[NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:100.0]];
[superview addConstraint:[NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
[superview addConstraint:[NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
Utilisation du langage de format visuel
Il existe un moyen de simplifier la définition de la disposition automatique des vues à l’aide de VFL. Cela peut sembler difficile au début, mais il est en fait très facile à utiliser. Quelques définitions d’abord :
|
représente la supervisionH:
ouV:
représentent l’orientation actuelle - horizontale ou verticale- les noms de vue doivent être mis entre crochets
- la hauteur et la largeur de la vue doivent être entre parenthèses
- les marges sont spécifiées entre les vues et entourées de traits d’union
- la priorité pour une marge ou la taille de la vue peut être spécifiée avec @
Exemples de syntaxe de format visuel
-
someView
est attaché aux bords gauche et droit de sa superview sans marge :H:|[someView]|
-
someView
est attaché en haut avec une marge de 10 points et a une hauteur égale àvalue
:V:|-(10)-[someView(value)]
-
someView1
etsomeView2
ont deux marges définies entre eux -value1
avec une priorité de 900 etvalue2
avec une priorité de 800 :H:[someView1]-(value1@900, value2@800)-[someView2]
-
La hauteur de
someView1
est égale à la hauteur desomeView2
:V:[someView1(==someView2)]
Exemple de code
[![Exemple de vue personnalisée][1]][1]
Définissons une nouvelle vue, qui a un champ de texte et deux boutons avec des hauteurs égales avec des marges entre eux, et une étiquette en dessous. Les boutons doivent avoir des largeurs égales et l’étiquette doit déborder sur la ligne suivante si le contenu est suffisamment long. Cette vue doit être dimensionnée automatiquement en fonction de son contenu sur les axes horizontal et vertical et centrée au milieu de sa supervue.
- (void)addView {
// first lets define a container for our views
UIView *container = [UIView new];
// do not forget to disable autoresizing masks for autolayout views
container.translatesAutoresizingMaskIntoConstraints = NO;
container.backgroundColor = [UIColor grayColor];
// now to the subviews. this is mostly boilerplate code:
UITextField *textField = [UITextField new];
textField.translatesAutoresizingMaskIntoConstraints = NO;
textField.borderStyle = UITextBorderStyleRoundedRect;
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
button1.translatesAutoresizingMaskIntoConstraints = NO;
[button1 setTitle:@"Send" forState:UIControlStateNormal];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
button2.translatesAutoresizingMaskIntoConstraints = NO;
[button2 setTitle:@"Cancel" forState:UIControlStateNormal];
UILabel *label = [UILabel new];
label.translatesAutoresizingMaskIntoConstraints = NO;
// this line tells the label to let the text overflow to the next line if needed
label.numberOfLines = 0;
label.text = @"This label has relatively long text, that should take two lines.";
// before adding any constraints the views should be present in the hierarchy
[container addSubview:textField];
[container addSubview:button1];
[container addSubview:button2];
[container addSubview:label];
// now lets define two helper dictionaries, one for metrics of our view:
NSDictionary *metrics = @{@"margin": @10, @"textFieldWidth": @160, @"buttonWidth": @44};
// and the other for view bindings using a handy macro, which effectively creates a dictionary with variables of the same name:
NSDictionary *bindings = NSDictionaryOfVariableBindings(textField, button1, button2, label);
// lets define a horizontal format for the first row of views in a variable:
NSString *horizontalFormat = @"H:|-(margin)-[textField(textFieldWidth)]-(margin)-[button1(==button2)]-(margin)-[button2]-(margin)-|";
// this format defines margins of equal size between all views, fixed width for the textField and sets both buttons to have equal widths
// lets add these constraints to our container:
[container addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:horizontalFormat options:0 metrics:metrics views:bindings]];
// now lets define horizontal constraints for the second row, where we have the label:
[container addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(margin)-[label]-(margin)-|" options:0 metrics:metrics views:bindings]];
// another relatively long visual format string:
NSString *verticalFormat = @"V:|-(margin)-[textField]-(margin)-[label]-(margin)-|";
// this format string defines vertical constraints for textField and label, and should also define the height of the container
// adding these constraints to the container view:
[container addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:verticalFormat options:0 metrics:metrics views:bindings]];
// what we have left are constraints for vertical positions of the buttons
// lets attach them to the top of the container with a margin:
[container addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(margin)-[button1]" options:0 metrics:metrics views:bindings]];
[container addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(margin)-[button2]" options:0 metrics:metrics views:bindings]];
// the container is all set up, adding it to the superview:
[self.view addSubview:container];
// now lets position our container in its superview
// you can not use dot notation in the bindings macro, so lets define a temp variable for the superview:
UIView *superview = self.view;
// positioning a view in the center of its superview is not so straightforward
// we will use a trick from this answer: http://stackoverflow.com/a/14917695/934710
NSDictionary *containerBindings = NSDictionaryOfVariableBindings(superview, container);
// width constraint from horizontal format is not part of the trick, but is necessary to constrain container width
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[superview]-(<=1)-[container(<=superview)]" options:NSLayoutFormatAlignAllCenterY metrics:nil views:containerBindings]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[superview]-(<=1)-[container]" options:NSLayoutFormatAlignAllCenterX metrics:nil views:containerBindings]];
}
[1] : https://i.stack.imgur.com/phmdY.png