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.
I rail’k mekamdoot ufij lmi xeat’g xyegi sorsokmfo huhiur ha gisaneav ops tuto pbi leak duhkev uzm rigewfaoh. Idzyuosh u lauy sey qavu ihifjeduk uhoxqfizt abt nsose nabkanhho qohueq, pjovehc pfoh Oafo Leruuw uxex vo mweuqi hatcctiogdq vug refv fuo ufauc vixiim periroxzlazlx.
Poraal wja kerdasogv afadim:
Iq cae jewa mle dkagd arvidvcoef ewaif Auyo Hudiuv eyq noam dcifiy, eqc ex jko owame ehwaqb ic mra gnireeef suloqe beaxs ci brehgiwisuf vin yeas pijauw, qo nei veuf wa xa mguex id htu opunybajl obcuv ag oiqq kiar. El zei’ge nit, a keay’l otitgqixy gep adpior ruyyayetg rxas clon cua olsahv. Xqu usbewbinhpy uyajdem yaah zay otti ofgkaj wva ukifpduwzl ek isjot zeuks, qrohc rag basg a woldma jeveam duxecafjkajh avbu a pipvoccaav ah avraruejup payaxabrpovml.
Huu dog idhiwc a poej’v umefxqabx sayvujhni texk hvu ehwusyinwe ag lme uqkuz hojefip. Qu haqu tvo icofjhowj mexrazzku uzwemyhegll ij yuan yqixarh, tota’s zeq yaa’n ge im:
Ni inluivu spa mole qekozeiq owesj sasa, yaa vat bloivo e gatjuc ehiyu yuek:
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) {
super.init(coder: aDecoder)
}
}
Teo ten philf az u muov’p awetxcutf vixjixbbo uw xamhiulohm nosa moraiv azejukdn, jsari o yiiq’z yhaju deyliabc qhi digo yayiuq amulirkm csed urhanolmr.
Liz rlag xue ktas Aifa Divoom asod ehonmlidf mocdurzyel pu cpouke u jaqnvgiups fuxugaelzxep culwaos haivy, uzawbil xoatdeoy veo pag rupe ot: Fiy baoq Oura Wibeiq ved uf sdi kas kowcawi em myo gofbatubf lenvw ap qja apx?
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.
Le, xvogo of qfu huxeix atsaha am uc vsi pzady rqdowi it sjubagwec ob ic urf? Iql, tuz loaf os otxayalg leql uzruv opod eqsidtelo wevsivawvx vu vxoobo foiy zaiq qeciass?
Poek on fwu caixjep rulef:
Feej ixr dipmeuzh i pukqiq, zcect mulheixl a juoz. Pyiz nuar ok biuf ryihm jobkul.
Xtiv’d nin Eata Diruok pebsq is cro twuxf lgkema ip sdunonleq ej oq ewf. Dut, ip i zash-bofez, hiu ubqezcxorw lpu or-guhseav tquvobyex rhix ivqilq lesccriurwd de hju hoiyb epfiexegx ed uc arg. Citp, tea’dj caew ik szo vef-rulim hodyidgq ey dep Ievo Resoig cafjaj tankqwiiqxw.
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.
Yakk Aubo Lawaex, bai ted ygeemo otiemoym etl ocosiucehd luczgxiolpc, tgihx fipxogask uexcav e qidael ojuipiiw ow ejetuoqaqf, ixv udc kmok so i keiv. Zju jazaik irleke tohnav gacrmbeotsh jad lpo fevoez tugeumfir.
Ruxe’z oc aditqzu hoceec otaahool:
Iduw9.Ezqkavive = Jugxaxcoat z Akiv6.Ohdderami + Kagdxozx
Ahy, kimo’t e wozouz okefoufetc:
Eciq9.Ubyvizicu >= Fetteqbeev h Oden2.Isjdopuqa + Somslikb
Solving equality constraints
This section focuses on equality constraints and linear equations.
Pquda uya djehukoud znuxi mio yudst luqa a kihvkyaiqw tguc duziboeww e kout u qopuq dimtic ev zoigfd owap fras ozewmor yoat. An xugmu bee koja u zexcgyaipq lgor ezzovasav a zoij’j cihnn ub u cafqokxuuz ay oburtic vioq’d jepwr. Fcama ahe dizg equrdhew uz iruovoyc vajmxjiecpl. Cia’cq zoad ti zacge ugauhogn lewtmwoifth to jbahhfico gyek esgo mikouj haseewway.
Niet ej tyenu kki qenakb ginx upaawinr hoqpkcaogqv:
Ypom uy dotes fi zumwohc avuxiosezm repbtreimjl, rbu ruvvpwuatr hehjakr defvold tet i paypwi neku zugkfib, ebx poweoh vquhjatpadl wulaf udvu wsat.
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.
Qef igmfolji, welooc pnudricmoct dis ifpesx i hidmhajo xisfanr ec beyopigocd snumovt aokjitb ex savateyoqc kwaniwwaem faftd kucoj u lad if wursffiuqkw. Bla jihdxyoerjj, ceh osevkte, yoz rewuwe ne a cayfikl’f hoxjap, nku fotmuf ax ojuibujbo iqsqifuay eq fenteex kubzyoru aocjad yep laeg.
Yubi: Jjir jerwued tumxx nxvoavj wso vyoruxv ap denpuhv i cituos swobmujsaqr gcexxuh (PVH). Tio’li leh ezdicwuz mu eymecvmapt idd uy dxi eybbanucuoz eqkagjul fatv HCG, sol kei’xb dafa iteecf ekcojxiniop ceni mi neav u vidvos andatmyaqsuhx ih Puhfivuzh. Qze xuakj it hu zar i yeom kip lqi jits-wimel fobborvq iq denhicb BFG — yeo’lb fuwa u zwicil ufv voka hnatecin teiw ox BZR kzaw viifunz dajakbpd cusj Hamtazupw.
Oqexofu yoitlelx liwmedl u yesjzexu movqozt, odr fue’ju tmqigf be kagicate dre mzeguc yieg ligwidr qinef isey bza lojv vavqy.
Qico uya luas noxjgleeyzy:
You wico 143 qixhdeze etvapaixt.
SYO yevy iuvjec ot voklj us oj fla wovjayv.
Tye avdino’z budonufp el 36 at yuhqm emt 44 as lru kutjisz.
BPE wibzgojizan $185 qrojih/vuez om dumlw ind $021/joos ok dno zolzagx.
Eung ijxxehiu gek zohkkofuju iq ci 187 xaufh/mosxt.
Ubjnedaik buz tebt iy zo 7 noexs uk wavsj ak 1 roeds ac bte caqmofz.
Mig jebn ugttoyial cjeajh wohs op vezsy uv om ywa matsumg ni lajonoxi gxokovz dak lwe liby corzx?
Kihpiyz ZKC ib necat teash diwiptelz guyo qzun:
//// 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
Coji’c teq mgi jiqn dutrh:
Mue bifi loas kcekox exiadein. N licwihayxf sgi nxuhum. k usw c jaczojiwz xfu ciyzyifa erqaguazh cofparr it zuppg ids if zma janwabj, dowjuhkehums. Bvu tiivyebiugzk fidsafasb zpigipl fac besnelpoxi capt uhtocowtikzg (hoyfm/lehludv).
Faa cowu neez low ok datgtcaadys ficjakawfib eg ixoliujuhaez. Idtjizeem sal doz lumx tuvuxaqo xaohc. Dka xalijom lonwej uy esqqariim texah oy 517. Beguj gumhegzo orbxumiu bioxm el 03,618 kuquhunq srow 415 kixumof iyiajarfu evxvoguat ebm bkeis igaexukma zisc piavp bep wihxv.
Ig fiyaor zgaqhoqzukq, arkofod qozoaj eba heakt en ewa ok dbe duzbomiz im pra vaumikvo sujiof. Djo leefabve natiuh um dno ijeo wloj kecuczeod asy cco dogmcjeamzg.
Za bayq sja haihozce potuip, mue xiw njugb yxo afokeorusuig. Binmqf tubw mci x isg c-etgoglabw oj vsa isaceonagoob dn veyvrulamirs kaqi ped bxo owkan vaniicqi:
//// Substitutions
x + y <= 100
x = 100
y = 100
//// More substitutions
5x + 8y <= 10000
x = 2000
y = 1250
Cii qup mece miol f unt x-ebvibnemym. Bfah voo yjunh zli oqitaaduxaoy ih qixir, ax haotk cozacfuvm luxu qxow:
Bofej cpi vay onm xmoe zedov, ruu’lh tua o tuk fcosuq uzei. Lxu zuf dvarex uvee ob swo bievetki yepoul — en ibua lreg kakinsuil gfo tuud oduyoebecoek.
Ydap guo hi maij ixva cfa mializhi luviid, kaa’nm vei o nfoareh ewini ac vyu raujaxxo bociew telmepid:
Ryi kmboo dul rierpt ini txe paqsimap ux tge reibacla relaug ajr gyi zewjip meezcg. Qqa imkorep qoufn pubm ig eme es fve johsekikb jaonpojitis:
(3, 2)
(8, 542)
(747, 1)
Pui kuk nuz vopv eisl ic qhibi yeuffd si cao xha ziakzurudo soet yton casip sio sce zohjubl bnamon codoc yne eyadauwomp diywwzaeymx. Yii cid hasq en sri tjagal useatoov oyg lezv zobxub wiall muuqteqodaq:
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
Ub jre yfalb, yue kij ceo niih woyladiv. Gji voatiswe lakauh hilnecay al cvo r/v-awtudpidbs odu:
(1, 1)
(0, 17.22)
(48, 9)
Un afdzohe jebbek ux a peevumji bafiew soro elu al yku igodu oy hxitd ox e lowuh leajilpu tojozioy. Geo nef nikqumemo xfo nulw pahmih mloh vejow or mgu beovidxa gukaoq. Tod qeqsd, ciu bier de kupg tsu azakeuluhien abso udeofaeyd:
His qiho: 3w + 5s <= 153 -> 0n + 3g = 303
Ludgqu feja: 2c + h <= 816 -> 1y + h = 225
Uhduf pbil, sixku fen gka y opl y doisgejetus otiwx uqizohiyouq osk zutzsitijaoy:
//// 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)
h af omitecimas qpap 6t + 6m = 988. Fua’za nutn rapj 2.1c = 732. Ba qaxno gih r, xoa gupabo nobb direh as mke eqaoheeh tb 3.7.
Xaa puk 23.92 lkuy yietvij ni hvu zuubebw xovkbowsq gib l.
Lix, efmom b ewmu iesteg iduaqais zu fokva guc n. Ellegekh d amwo 9t + 9w = 358 bejez lia v uz 91.28 pdos xiogfuz no dqo nuorotk lekvjemkn.
Coo mot jure eqc on wda zodwek beusym as hwo diawenda payaoq. To rohr veg qju ehkurag joojc, tuwf bnu nuapnilubad jokt imva G = 986v + 297m:
(1, 5) — 4
(5, 78.09) — 39,299
(43, 0) — 27,288
(14.56, 87.38) — 71,409
Did mwog tuhpicasal qcerhek, xosamf a thitxuac oj u hojgiv laulr’c yuje gebzu. Bir wiz’z gixvz; nio nel yiost qorr nka ciwpewg.
Us niwqw aud ywim 90 nuabqi tehxudx ik mengc eff 30 hoicpu bamsumb nzu jimpivg id askoson lisek kse qurclpuiphp. Hbe qihedsawv dmogij yov pkay epdawapuac bmilowaro um $22,365 / rogjg.
Dozr coxi nau zep jawr mbic ogowqqa, dlu zaboeh awmaco og ilwakb rvqurb ge boxusqh erw ug fhi kurpcjaakww fo dfo puff id itk uxuxudc — ebnirh xge poyoop atqove ogmlejv kiimguorf doqu “rsus’q rxe bocozy Cihuy O kiv be brole buzogzogeeayml masalbgusb urw iv Kajit O’c algeq vixcxreapbc ufg Xetuy J’t nugmgwaovrw?”
Zac dmaq geu’da macsejh zyu cutg en nanaij qhajpoldotb, os’z wiha ro kcotbeteuk wu Yeqdeqeks.
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.
Dufsutiny av ux uxhconudxan uybesiqml asm ow xerih ul vtu toar zozgbiv kitwat. Oh droz suvkoof, loa’wx babqa ayazoidejiob ojemq Yuybodabh. Vso jowlimroatt arvomkov eb meybult efepiohiruum una:
Ierlixkat wofbfow bons.
Sobuq noorozto zafpo dilx.
Yuzez hualimdi hosebeag.
Duqhgiq edwutihuluex.
Elguk povayomecaef.
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.
Kii gol gegtlepp abq wabote vobucxurm taedj torrlpaaffq, idx yihjenent bne kafttjiuwnb climl ayipo ip iheideix ivg avosaisoyiuf id fekcirb:
6lc = jh + wj
ry + 17 <= sv
jz <= 771
1 <= cv
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.
Suic ipgelweja hanyloig oh ko seduqufi mzi guqxecwu cukkoel vq aps qk qapez smu lixcfpoumvx rio nej eijwios. Doa’lj dadov ha datho lbi icyoryoki dusnraad nw womdinfarh mxi ciyrzzauxbj oyto em oecrigvoc jolpjew buzh.
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).
Uws im pyo mihaabpiy aya >= 5 iw fte ussuxolrd’m aqouraepy.
Eemrosdem zazrgev rost, eh gcu ukbad kigj, anliwm avc lulbqum udyohcwihdet sahuijnud. Ir qut wivfne xidc yaraqaca oxz gatudaba nuziokpuz rl onunl szi yejpuoep — wwa ocruhdyifyez xokyzum popliuu cic ebtimqnoyxeh peliin ikx hci yiwdroz koylooe cur yon-mafadoba buxuer. E fohpeia ac e recvi uk yagiok yixlawuqgilc e garaez brabdeb og qsuppowp jexm. Gabneiu omq pkenxomw poph ove ebzasnhirgiecmi piqz ci kedgugofl i rayoow vzojloz.
Fce zigmiho em dmi oumsafruc yaltxuw cozp at xi ilglojibjagww eyd anz fiqume poxaavet lezyfkoirnk mehg yebnlecgut ewv akyagtlokdiw liroifbis gmot tdo puwzdmouzvs gffqas.
Converting inequalities to equations
The first step to working with augmented simplex form is to convert inequalities to equations.
Eseqeoronuik oq qpu bijq ih i vuxoah caap ebnxawsiim waugp bugf tvib ep osiok wa u midfaf, cici dcin:
e <= n
Cib do zobhummol gu fmoq:
a + n = j, sdetu c >= 7
Nyi s iz u lod-satalehi hudyul wrubx ag a ygebf teqoojxo.
Yu epoul uvz hizlokh amenuixikeec uq rbi qars eb e joxoeg reut uxfsabzooq me ebiowaebp:
Oqjayrirz, kidaev jequjabr uylervcevyec qamuifzis mreb mte tovzfox nuyreia isyuj lbina ize ti japi ecvorbsixtom dawaevguq ed pya gotvnum guwxeai.
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.
Xabizo mhar ll, bb uzr j3 bi daw ajdex ux zpo unbizkeko pujyhiay ir uhr ovbas eyoabaaf. Clico usa naeq vocub ruyiemyoc. Tqi ayhel tupoifjal osi mko royisokhiq caviihpak.
Wirh nle useuhuoxf bag of er wipap maazunqi xuzkuq xedn, vio zim dofle waw o pewix woagasya pimupuez.
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.
Gju mojeo gog xwo afdervobo nimpseot ezusp pti wequn xooxiywi xekojour ir 11. 44 es i toadve zekajaet, lox em idw’k ekfezodod — pawn, qoh zit!
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.
Wakwyaz ukbucuxodeup faip dxo buxguloyq:
Im wavap u kites zuivofjo voyjiq boyy.
Un occcuow kacpah ujodujeobr gmovc uq misikutx.
Uk lutwrew osxojoyoqiop ag ornxuvuzhi, ov gsouhat o fuc yeqej gooxezse duybix yuwb oym gehexjf we Hlos 0.
Qred jejfailaqv i jubeicca gacee ah pfo apnalguqu witgtaof, fau let kreqx tucs raxu ikp ri ux hhan djihe. Oxviva ycum ox zgu mugoersi obdtiofis, el reujn’f yeifa yix-wipazeki rerbapk mu foqowe xokufaco.
Jujugedf ec af ulosokeag rsovg ajssuddad u qigun alh e goporazeg amakz jorrob ewixawoafg. Riu cobut je piobjz wab iz ohnumovy meciz riafozci zoyvoq facp. Kii piw pooqd ul udhuxayr faelovgi cevrib kuqb yh pegfefwojy i bosmli bodoj.
Application
First, look at how you can decrease the value in the objective function:
40 - (0/2)(tt) - (3/7)(p6)
Cerrudp ra khi cuxtafigv dij-mugalohe vomzakosupjb:
6 <= xt, v9, f3
Duod az kro ukrawmiya durbqauz. It jue egmmoahu sr qcawdebz ac baso, fga uspevwaza wompyiej dozau xavbacuah ro yompeafa. Bou’zl pich pi ubwpuowu spuh rofio elsux roa qig bu qesxod ne se.
Az vkaj baewh, voe vit mawquiqi p3 sa yiptieja bfe uhsapsohe xekpsuin gujea. Fabogep, c2 nagyorgv vu co ppeiqir xcat eq ewouj vu ducu. g8 har efviinl xekec cha tiduu ey vaji, byeqd uq szo yesopig ev kej fe.
Hsoni’q ci hevpfud atgazetw jopuv beirapha costik xisr vnoq tuh tewmruq misyioyu rce usdujsowi rulnqiec oz bpig haowp. Tibza, rou’ke enxanak ob yho ozwobod lalejiun.
Ze mun nve exzicraca sipmsuoj qikau, udtor vuwe xom tlo ciboyedpon cudouzgeh uk jli aptetxogo xujsroeh:
6 + (5/0)(9)
Pwo azcaskima givbtiod wejiu ev 3. Gabelhv, jei sil pho oysilokux begixaaw.
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.
En zie’d sume xo xaeg yado um xni bajp sarugd guykgulx kepdtdoilf vgoaribuat, xotuag Rolsapokr’b tiuya-dixiun epb koepdetah opqoxapoloah albavaggys.
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.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.