Auto Layout com NSLayoutConstraint
Crie interfaces UIKit adaptáveis em código usando restrições Auto Layout, para que as vistas sejam redimensionadas corretamente entre dispositivos e orientações.
Auto Layout com NSLayoutConstraint é uma aula grátis de Objective-C iOS Development for Legacy & Enterprise Apps no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Objective-C iOS Development for Legacy & Enterprise Apps, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Objective-C iOS Development for Legacy & Enterprise Apps inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Why Auto Layout?
Hardcoded frames break on different screen sizes and rotations. Auto Layout describes relationships between views — constraints — and the system computes the right frames at runtime.
Constraints Describe Rules
A constraint is a linear equation: one attribute equals a multiple of another plus a constant. For example, a button's leading edge equals its superview's leading edge plus 20 points.
Disabling Autoresizing Masks
When adding constraints in code, you must first turn off the old autoresizing system on the view, or constraints will conflict.
label.translatesAutoresizingMaskIntoConstraints = NO;Creating a Constraint
The classic API is NSLayoutConstraint constraintWithItem:. It is verbose but explicit.
NSLayoutConstraint *c =
[NSLayoutConstraint constraintWithItem:label
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeading
multiplier:1.0 constant:20];Activating Constraints
A constraint does nothing until activated. Use activateConstraints: to turn an array of them on at once.
[NSLayoutConstraint activateConstraints:@[c]];Anchor API
Modern UIKit offers a cleaner anchor syntax. Each view exposes anchors like leadingAnchor and topAnchor.
[label.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:20].active = YES;
[label.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:40].active = YES;Width and Height
Constrain size directly with dimension anchors.
[label.widthAnchor constraintEqualToConstant:200].active = YES;
[label.heightAnchor constraintEqualToConstant:44].active = YES;Safe Area Layout Guide
Pin views to the safeAreaLayoutGuide so content stays clear of notches, status bars, and home indicators.
[label.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor].active = YES;Constraint Priorities
Every constraint has a priority from 1 to 1000. When constraints conflict, lower-priority ones yield. Required constraints are 1000; flexible ones use values like 750.
c.priority = UILayoutPriorityDefaultHigh; // 750Intrinsic Content Size
Views like labels and buttons report an intrinsic content size based on their text. You often only need to pin position, letting the view size itself.
Debugging Layout
Conflicts print warnings to the console listing the fighting constraints. Use the View Hierarchy Debugger in Xcode to inspect frames and constraints visually.
Quick Check
Test your Auto Layout knowledge.
Recap
You learned Auto Layout in UIKit:
- Constraints express relationships, not fixed frames
- Set
translatesAutoresizingMaskIntoConstraints = NO - Create with
NSLayoutConstraintor the cleaner anchor API - Activate constraints and pin to the safe area
- Use priorities and intrinsic size for flexible layouts
Auto Layout makes legacy UIs adapt to every device.
Perguntas Frequentes
A aula “Auto Layout com NSLayoutConstraint” é grátis?
Sim — o texto completo de “Auto Layout com NSLayoutConstraint” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Objective-C iOS Development for Legacy & Enterprise Apps, atualize para CoddyKit PRO. O curso de Objective-C iOS Development for Legacy & Enterprise Apps inclui 4 aulas no total.
O que vou aprender em “Auto Layout com NSLayoutConstraint”?
Crie interfaces UIKit adaptáveis em código usando restrições Auto Layout, para que as vistas sejam redimensionadas corretamente entre dispositivos e orientações. Você pratica Objective-C iOS Development for Legacy & Enterprise Apps com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Objective-C iOS Development for Legacy & Enterprise Apps?
Nenhuma experiência prévia é necessária. Objective-C iOS Development for Legacy & Enterprise Apps no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Auto Layout com NSLayoutConstraint”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Objective-C iOS Development for Legacy & Enterprise Apps?
Sim. Cada aula de Objective-C iOS Development for Legacy & Enterprise Apps inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- UIView e UIViewController
- Controles e Eventos Comuns de UI
- Visões de Tabela e de Coleção
- Auto Layout com NSLayoutConstraint