# 14 Under the Hood of Auto Layout Written by Jayven Nhan

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

You can unlock the rest of this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

By now, you’ve learned the different ways to add Auto Layout constraints. However, you may be wondering how the Auto Layout engine works its magic. Spoiler alert: It’s not magic!

In this chapter, you’ll dive into the inner workings of the Auto Layout engine and discover the math that makes Auto Layout so powerful. This chapter is less hands-on than the others, but if you’re curious enough about the math behind the magic, you’re in for a real treat.

This chapter will answer the following questions:

• What does Auto Layout use to create constraints?
• Where does Auto Layout fit in the grand scheme of processes in the app?
• What’s the purpose of solving linear programming problems?
• How can I solve linear programming problems?
• What’s the math behind solving equality and inequality constraints?
• How does the Cassowary algorithm work?

Rest assured, Auto Layout isn’t a framework made by wizards from Hogwarts. At the low-level, Auto Layout computes arithmetic algorithms. But before looking at the Auto Layout algorithm, you’re going to look at the differences between alignment and frame rectangles.

## Alignment rectangles versus frame rectangles

As you already know, Auto Layout helps you layout many views using relativity. Unfortunately, there’s a common misconception on the “relativity” part. This section answers the question: What part of a view does the Auto Layout engine use to create a relativity relationship with another view? In other words, what does Auto Layout use to create constraints?

### Theory

It’s a common misconception that Auto Layout uses view frames to create constraints. It doesn’t; it uses alignment rectangles to create them.

### Working with alignment rectangles

Look at the following image:

``````import UIKit

final class CustomImageView: UIImageView {
override init(image: UIImage?) {
let edgeInsets = UIEdgeInsets(
top: 0,
left: 16,
bottom: 16,
right: 0)
let image = image?.withAlignmentRectInsets(edgeInsets)
super.init(image: image)
}

required init?(coder aDecoder: NSCoder) {
}
}
``````

## Fitting Auto Layout in the big picture

In the process of view layouts, Auto Layout seems to “just” compute view layouts. Then, your user interface looks a certain way. This section covers the in-between view processes.

## Solving constraints

Auto Layout uses Cassowary, a constraint solving algorithm, to solve constraints. After placing constraints on a view, the view still needs to determine its layout variables. For this reason, you need a constraints solver. Cassowary helps translate a view’s constraints to layout variables.

## Solving equality constraints

This section focuses on equality constraints and linear equations.

``````labelA.frame.minX = 16
labelA.frame.minY = 16
labelA.frame.width = 200
labelA.frame.height = 100
``````
``````labelB.frame.minY = labelA.frame.minY
= 16

labelB.frame.minX = labelA.frame.minX + labelA.frame.width + 16
= 16 + 200 + 16
= 232

labelB.frame.width = superview.frame.width - labelB.frame.minX
- 16
= 667 - 232 - 16
= 419

labelB.frame.height = labelA.frame.height * 2
= 100 * 2
= 200
``````

## Solving linear programming problems

Linear programming problems ask questions relating to how to minimize or maximize a variable given constraints. Linear programming is a mathematical technique used in solving linear equations. Whether you’re looking to minimize cost or maximize output, linear programming can come in handy.

``````//// Profit equation
P = 600x + 400y

//// Variables
x = # of SWE working at night.
y = # of SWE working in the morning.

//// Inequalities
// Employees can not work negative hours.
x >= 0, y >= 0
// The number of possible employees.
x + y <= 100
// The number of possible employees hours.
5x + 8y <= 10000
``````
``````//// Substitutions
x + y <= 100
x = 100
y = 100

//// More substitutions
5x + 8y <= 10000
x = 2000
y = 1250
``````

``````P = 600x + 400y

// (0,0)
P = 600(0) + 400(0)
P = 0

// (0,100)
P = 600(0) + 400(100)
P = 40,000

// (100,0)
P = 600(100) + 400(0)
P = 60,000
``````
``````//// Inequalities
x >= 0, y >= 0
x + y <= 100
5x + 8y <= 590
2x + y <= 100
``````

``````//// Elimination
// 1
5x + 8y = 590
2x + y = 100 (multiply every value by -2.5 to cancel x)

// 2
5x + 8y = 590
-5x - 2.5y = -250 (add values together)

// 3
5.5y = 340 (divide both side by 5.5)

// 4
y = 61.81 (rounded to the nearest hundredth)

//// Substitution
// 5
5x + 8y = 590
5x + 8(61.82) = 590
x = (590 - 494.56) / 5
x = 19.09 (rounded to the nearest hundredth)
``````

## Cassowary

Cassowary optimizes layout computations for interactive user interface components. On June 29, 1998, Greg J. Badros and Alan Borning published an academic paper titled The Cassowary Linear Arithmetic Constraint Solving Algorithm: Interface and Implementation. According to the authors, constraint solvers at the time couldn’t efficiently handle simultaneous linear equations and inequalities for graphical applications. Hence, the birth of Cassowary.

### Sample inequality constraint problem

First, you’ll see a sample inequality constraint problem you need to solve. To prime an inequality constraint problem in augmented simplex form, you’ll represent the problem’s constraints in equations and inequalities. You’ll also learn what an objective function is to better understand its role in solving a linear programming problem.

#### Constraints

For time efficiency, you’ll solve inequalities in the horizontal axis. However, you can apply the same logic in the vertical axis context as well.

#### Problem/objective function

In linear programming, an objective function is a function that minimizes or maximizes for a specific goal. The objective function is the problem you want to solve in linear programming.

### Augmented simplex form

The Cassowary algorithm builds on top of the simplex algorithm. The simplex algorithm is a method of solving optimization problems in linear programming and it doesn’t take negative values (un-restricted values).

#### Converting inequalities to equations

The first step to working with augmented simplex form is to convert inequalities to equations.

### Separating equations into tableaus

It’s time to separate the equalities into unrestricted and simplex tableaus. Initially, all of the equations are placed into the simplex tableau.

#### Application

Looking back at the equations above, you know that 0 <= xl, s1, s2. These variables have values that are confined to any number greater than or equal to 0. They’re restricted variables.

### Basic feasible solve form

You started with inequalities and converted the inequalities to an augmented simplex form optimization problem. It’s now time to solve the problem.

### Basic feasible solution

As introduced earlier, a basic feasible solution is an extreme vertex of a feasible solution region. You look for these vertexes because you care about maximizing or minimizing outputs when solving linear programming problems.

### Simplex optimization

The simplex algorithm finds the optimum solution by continually searching for an adjacent basic feasible solved form. The adjacent basic feasible solved form consists of a basic feasible solution. The basic feasible solution decreases the value in an objective function. When there’s no more adjacent basic feasible solved form left, the optimum solution is found.

#### Application

First, look at how you can decrease the value in the objective function:

### Error minimization

For constraints with a non-required priority or priority < 1000, error minimization comes into play. With non-required constraints, the layout engine goes through additional optimizations before providing the final variables.

## Key points

• Auto Layout uses alignment rectangles to create a relationship between two view items.
• Linear programming problems are minimization/maximization problems.
• Cassowary is a linear arithmetic constraint solving algorithm.
• The Layout engine uses Cassowary to solve equality and inequality constraints.
• Solving inequality constraints using Cassowary consists of working with augmented simplex form, basic feasible solve form, basic feasible solution and simplex optimization.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

© 2022 Razeware LLC

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.