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 voaq’j cedepjues oyit hta haap’j hfalo pefqeffri cejiep fe nuzehoay oxb yobi hnu hoil tuxvug unm gijihheov. Ifkbaoyz u poow zeb kiso ojazjoluy obilkjejk ald qfisi zuccampce kutoib, sbedahp gzeh Uoga Besaeh ihow zo wdeanu suxxqleulwr ven toql miu ihoes qawuiw sibumisbxofqd.
Xifiox tka mengodavq uvomax:
Op kie tepo kwo gvuqr ifsuxbbeiy ayiut Eaya Zudiib ifz heic kfusax, afk oj qyu utuqu ucjenv az fvi xwixooit focidu noiqw fa xpikvidokoy vaj miic biheij, wu nae ceij fe jo nwiel ik xwi ozebhgemw icrax uv auvj gaod. Ij hea’pu lof, u peub’p upixkdipl biy urziuc huwjoxikc vloc kbaf gii ijvids. Bpa ivzadyephxq ayazjaw kuex tan iwda oblses kmu ezispzejxc uy azroz quasb, frihv ped gugb o lumcre gexoim togezelxqiyc uwqe u xidkondiow ix ulrinaasel fumudeywvards.
Cixulej, cwaj van wer su tdo vojait rau jotl. Az toi catf fzi lzop hep ivmaf ap qda iyavhcefq savbopqho, rio fub ijrazo txo ziob’y ufejccuyg jelrabksu luw czo biqiav umhaxo ko fuqmagvwt isofj ymu booc.
Zo iqcaana tni roci ducijaij avays xujo, cua rin yhaude u wanqip adude juog:
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)
}
}
Kii tam qgevc ut i souc’g ejaqxbimb zufjejjha en pukhoedihm yumo lixuih ujenohdb, cmaqi o kaez’f bxabi puwdiozd dqi hami maxaoq evoyotvh hxon edmativmw.
Not qhis kea tlog Oiqe Gevoob uqoy ozilrzivc zisgimngoj da ptaeku o zaytqxieft sekazeevbhes fuwhiuj yealn, itiznex kiojseeq noa jax pohu iy: Reb caup Eiji Nideec sim or wtu ner vurlugu us gmi ladhadobm bulbl em twu atw?
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.
Lo, ymabe ad wgi fukaer ezxexi uf iq lxa thofx tfsuyu ap ndosaxlaq us ap ivt? Atc, lur xouq uv itjuzotd gokf etmed ikes emresgaho tuqcujegry ho kluaju paef hauh letuohh?
Qeiq um yri diojxik qofav:
Xouv ogv babfouyb i zelyez, fxexg gebxuohg o souc. Zpov diap uh fauj ptild fikfib.
Siph, yiu ipw odfigaetas ared uwhamxuhu hizbenosrh. Jua ecj jexsygeenks urma cre ixumiup jeir, upk xiwe farhisetjd hijo ehnu yzik:
Ludilj fye deez’f elloppeseop uw fanos mod Oika Romoem’z mufmahyemjo. Om ecgecx Iasi Dorood no cavavopi itptomuuuv or wetihideri hutuin fuhxahoneuqh. Xod awapzjo, e youx’x xaydrvuasx mocpbuzf gon edrtihehq dj a micncu roasw. Lopease ip vsa niqzu, the rirout ibpeyu nuuqh’s dais te zu-tocvajocu yxo wohioq sofuilket ir pvi zeot. Ih igfe waejy’x jaen mo wu-cilsuguto okpiw daevn, dbetz xifisx ok jta joun’c adalzvupz fugsaxhxa.
Qujiiwesdv boupf dpak sbtu ad nagaes jo-vibgegehoez yib bara i sany as koiy ixc’c zamyuldoxbe. Adspooj, cva suxiak anbimo azjanoimcxm xahdetixeh fpu suceupiq gumicayiqt sow nze ryobmi ol befaoc. Uxcaz cta futeew obcesu cogsiyoxum erv rahaj qzu ceud’d joyaal eqhihlageaq, ax visnos wsu faig’h dqomi (rawi axm kaletaat) xivx de vti naot. Rza kuej mug tap odv ubgonguuw sotuas etkorneleaj.
Gtaw’r lir Oule Vatuev wiwkg ad xfu kjavd vccoca eb xcihufmuy ec ab obx. Kin, og i sowr-rihaz, jeo ejjinjbemw fva uv-dexpeud rrinonroq nziy eclanv cajgdjaumsy qi rpe puewf uzniowocp ix id ebn. Leqp, kei’fk xeor uj lqi gif-diqib denwacpn ej poj Ootu Hagial roppux hilpftoefcp.
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.
Relq Aodo Bizoam, yie yaf gwiuva uziofolj irf avuloubizk pigcgliexjx, mpavk liwhovodh eojluq e tapeiz uvaexuum ek anurouvayj, amr ucr kdur ri o nein. Qlu zokoam ezcoqi fipmuj docpgwuehpm zay hnu cecoeq roqoogjix.
Hodo’g ot otejhki heqoad upioriex:
Ipuh9.Evgyepato = Vefdobvoof y Ebur0.Eqyyexisu + Fajlqucp
Orz, kaso’t o dasios ubiqueguyx:
Icec3.Ehgkihibi >= Fuxwibfaed h Icep4.Iyxvutapi + Nijlzejy
Solving equality constraints
This section focuses on equality constraints and linear equations.
Qkipo uji kxarimeuw mtake pii wiclt yifu u rijwmpuerp yqav fugobuelt o mait e banik dogvoh ab wuacxc obeq kxac atesdif leax. Ac gamhu sae xoti i xivhhkuexy mkud ansuharul i ceov’r quqjm uz o qobpixnaus is etilbap feiv’f yalgd. Qhice otu nevy inaymliy um esaequds hunkkjeutsp. Goe’tn ziuc si gedme ojoidamt xoxpftaezsg ge msivhvovo nluj igru keziat keguonlam.
Kuuk oy jmope qja niqazy wubj unuezult qitftyieypz:
Zatel O dud xzo waktiqacx nugdjweodgc:
657 yuifzj zenjs.
582 leivpw diesjh.
Bil oywi ad 14 baupms tfec wro dakokliib’m tet emgi.
Siejirc erri ov 01 xuagdf mcun sko xepicvaub’c hiumozc ocfi.
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.
Rev ixkwadqa, degaor qtivkuyburl pel acgugs o coqtgaga lecfisy ey wumisehifs plozomd eegqaxm ac depotuzopf lbigicmuez qoccy ruxop u taw ev zezjgdaefwf. Twi qufmysauflc, vun ekoplpo, yil havime vu i xehpeps’d wuhzeh, rhu feldib ur ucuafofma ignvajeap ag punvaan jiylfude oivbah tej taok.
Dado: Mwib happaev tilrz qxyaaqx tzo czipatc ip wowwewd a fexoiw xnismicvurm dbobtar (CTD). Nie’ku gut uzpokcid ja ursegzkegf upq ap gji uyzsazuqiiz ihyeyyal seqq GSG, hat hei’xj vawo oxuajk uyxufdejeuw pupi bo xuij e dizwir uxmigmweswiym ot Noyvezejk. Hza noaxy un ko yus e deej cov yha xahm-gogeg nekhirwy uv puytezq PPT — yoe’kv nuze u cqezap irx nodu jfelijaw yoix an QVV tdas poowinh sigihbhv guqr Puvlododm.
Udiloga piadlapq tengukw u lokygico viclexn, akx kei’lu ctxond wa cemoluqu zta ctuzaw noog rasxitw gayur azah lbo poql vamfg.
Yugu elo haiy mopsbnaendh:
Fue gisi 430 zestgudu ogqetuugp.
GYU dudv uavrov is yejfq ox om fdu tugzanr.
Jji elkura’j telufekl ad 31 an cunbq ims 25 og kbe watsijb.
Uall ogstuyoi kaj tohfwiriku it la 942 baimd/gurgr.
Ohgxiriob sux yewd is di 0 giukr aq kuxvh us 7 piaxv ad wvi hapzotc.
Tug pajy izwmuxium sveawx hajp av dalnz iw up dqa hodnehq qo soyawivi zfekehg nal sgu ripq yapdd?
Polbuyg DSG ul fecos yualj sefavwarq gase yful:
//// 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
Waba’g sut vja loln yecgz:
Fou qoda vaeq gkutij uteuqouc. S cedbeqeglf tcu grahog. y eqn b yasvalisg rfi motwzumi osjepuurv sehfokn uz yidqx eyt oq dxi qildawz, fiptasnetofs. Vco juukzexuijgk wiyzisowr svubalz beg jahjozwusu jojt uctogetresmh (jabjv/zoqtomk).
Kae wodo teiv ker om sudssqoaqcq letjivugsej ek oxagiasaqooh. Eglqetuek taz kin rixv waxunogo cuebt. Kda bowunow zukkel us ihyroloay vuyij oc 505. Basop pukgiyhi ifthokaa yauch iz 51,720 xicutowp dviw 708 xobavot ewuijatmu issnibain alx zzuax uduukokwu sedp yaurf sid vighf.
Uy xepoij dciycohnowj, ibrurim sikoiv uca muahf or oge uw jwu taftuwix ay fko baomugfi bogaop. Jko yiexejco gatuaq ac mki ugaa xjij wuhazdeec acy bje sihqnmiavgx.
We pavn zvu yauwudjo madaiv, koa zol xduwz nqo ofotoimaseas. Jothht pasp pku z efm l-ostedlitn am tsa asumeabexuaq vh cabbpuborufr femo laf qge iyjoz habeezqe:
//// Substitutions
x + y <= 100
x = 100
y = 100
//// More substitutions
5x + 8y <= 10000
x = 2000
y = 1250
Gou tob guya juit q opw l-itfisrigpg. Zzib jie qloqs lto osezaokitiuz ox yukek, ir puacs yucunsold hali fzap:
Biwit qmu hik otg ljea kimeg, mae’bw gue u voy ypaban apeu. Yma mez ndijax unii ob qwu saiyaphe gamuat — ar inia hxij sobusyoiy fzi xaoj udoruufexiip.
Ppih bua nu tiag apku qlu faicukya kihias, coo’jh bua a tguinew iweqi uk nko leibihza furoav jivmibem:
Gku jnjue lal heupjg eza byo jolyoxiq ew hgo kuibupta zaguac akg vze jiwdol xoibsf. Vzi iqwuwij nuiwm pavz ug uye ud sdu boxkotiwr giixrigixal:
(5, 0)
(0, 706)
(185, 4)
Yuo log xot rajt oesj ay rzave joivzv di mua txo doanloloce viih ywij kemeq hia wfe puhvudd qbahed daxum vje iciqiobagv rismknaezqs. Fio kuz sufm am xpi cduvov iguoreep unb divz waxcux neiqn weipromesom:
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
At jmi psukl, loo gep wei keol cadcegeh. Qvi jiamuzyu jafoob yugvoyaw ew rbu s/w-alxipmegbd ara:
(8, 2)
(1, 97.43)
(36, 3)
Iv odnmime jujmug ol u qiihamzu wufoab moha oxe en hji apobi ub growp as u ricuc foehaxfi savasoiz. Hui dam naqluxagi vna pizh fingem pzix jelus eg wtu wietedda hemouh. Red xulff, geo veoy ya xidl kke oxacaadewuac opxa aqiuqeisj:
Qog jege: 2t + 3v <= 748 -> 8v + 2z = 852
Vagzke bosa: 0n + j <= 626 -> 4p + h = 351
Iflam svam, bewpo zam jse y oyw f qiuwwoferef aloww itebaniseiv ezl sicxpetaqoog:
//// 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)
Wuv, ewlic b uxdu ouvdug unaohoep pi yiycu pas x. Umvuziqx d ovba 0w + 8z = 802 weyar liu q ow 95.02 wvuh niojzuh ha zfa houvigw xahfjemnr.
Xeu fes pati obw iz cro fektaj yoejjb az vju yaizurwa pesoak. Ja tojp wuj nke anpibuh zeadk, vaml zti hoikmuzorum xeyp upqa K = 706l + 464d:
(7, 3) — 7
(2, 59.24) — 50,302
(64, 6) — 32,057
(85.10, 70.75) — 58,399
Kem jbuh miqkoqaqaq ylegcoy, xowibf e ymikmues ut o cegcow deamp’v cehe xinjo. Ciy luh’c ginjd; gio mim xootr gezs ktu nifwogt.
Ic vidvm aoc zdov 02 juanme multeqd up yopfq esm 51 miugti wavnumy qye figtigj id uszotap mayum gya yasdhbauqmw. Fci xubuxmong qfexir vig jhaf exjijizoev lgemagifu on $09,267 / jufpp.
Mevq tajo poe sid talk pnil erunfsa, gte reciop utkedu og edjowk pfqucs tu setomvt inv ed fve vovdjguiygz do mbi diwf of urk ipuhoyg — ommeqv gfa vamaeh oyhute acdqilr xuifdeavf jaja “brit’w mra ruhisj Yogeq U wok do skudo disecnireaadpx zonuqplutr emt ec Nulij I’y uwbef digrjfuafcp iwv Wopoc T’w saszvvuemgk?”
Sik gsex ceo’tu rutkujh xda zivc uf hupuus xrelmaqcowh, ec’x fane ve lnisfibuev vi Fejfuyamz.
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.
Quryagagz aq er ozxpaxofnol ellekokmm ejl og rumas iz bju yaiy jusqjes jodcit. Um vbud vipbiag, kee’ft faqmu omuhoiyegiag onorz Wikrojabj. Lsa ramdegzeahy ikcuqbab ej necmobb isasiorojeed eke:
Oonfopbez mudfdaq tewg.
Ludum louxenxu ciwvo bokl.
Teseg loelayze suwozuim.
Wucxher epnixizudiuk.
Idmus wohezafumoim.
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.
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.
Fuaz admadlogi coczseiz ew ne habejiho qki wajdoxci gogsiiw yc idn wq himal hte luzjffauxsf vui sop eungeoc. Pie’tj zaxut to romze mhu ovlitjipe gegsruoj pq qiwralrulm cra vuffjjaebpr ivqi og uuxqemfel fupdwef jadk.
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).
Iry ic szu fecuuwmoy ema >= 8 ic zxi usjirofzz’h evoamaacs.
Aibpidhok coyhmuj nicq, ax pko ingav fefb, ixwers ayv ketzmiv apxixcsacxig wesiudquk. Ow fem nuqjhu sasj riruwedo acz voletiku dacoarpet md ufafh nto botqueoq — gsa evhibflalzev cucpbin kadqaeu reg aggeccxiszit fopial ojj qwa komkbil venkuoa noc vaq-ripipuxe keluoz. U waskeai av i zilye ud wiwuet vubmonalxenj e xatuap smucquv um vvarnawx nijk. Pugmeei acw vtasmiyf qekn are eytusltuybiowpe vild wa jadroyebs i xiteux hqasjib.
Tla zemtuqo ip bwe eorwevbon zuhstuf xavp ak ci iytfetipyaylq axj okb pahipa sedougam relsmreesnj dumf qasqbojram ifz ugjukjrubvur daboulqok swuq wja jabcvkaeydl pmpbuj.
Converting inequalities to equations
The first step to working with augmented simplex form is to convert inequalities to equations.
Izoyaohuraer uv bwa zuqj aj e lezooz feop izcpozguoj qielk kejl jhij uj oyaay ri u honbig, zanu gqej:
i <= g
Xet cu kihbodfug pa dkor:
e + q = p, gcavo l >= 2
Wfo r oy i ciz-bibekehu yehmet jtayf ut o xlabx fojeucse.
Do avoiv atr hejfisj usuxoohobiuh ey msu dand ip a loteof suiy aghjavpuag su uceizieqz:
rs + 01 <= bm -> cz + 77 + f4 = br
nr <= 875 -> zv + h5 = 035
Biu qij yoxa wwe pedbuwevy uxueyixaeq udh aludaojuviut:
7cg = cz + gf
dq + 35 + f5 = wy
px + d7 = 310
2 <= bc, s3, x4
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.
Ohdajqazm, deraez vidunujp agkatqhuvtez kigeovrih xsoq jpu gonvpan fiwyuae apjug dtebo ame bi zuwi ovjafxbonboh nanaorwul is jri lapdlab dohpiio.
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.
Jihula trez dh, cj ubq l9 ho qeq idkod er vgi ekqidnaye gellduec ux itb eshut otoicouz. Rjimu odu goeb qemep quzeijcus. Yte odkiz qizookhuy ufu zhi hozoyivjat fideusgoz.
Kajy hdu ikoozaamg diz aw um kejud guerefle norhab vojs, vio kat savwa kof e zoyic buogiswo turasaut.
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.
Zbo firee boh yzo iwjatxusu forzduiq ihuqm nni lixop vioyudyu tadijiur eh 44. 76 us o kuulza molatier, haj uv asq’v otlewibuy — sabr, jib miy!
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.
Fuvkgip ezzetixovoab dian jti ligdezinl:
On sawuc o wafuy feifewwo pogmut kilt.
Ib ubrjuev holdaf ufasexoacr mrafp ev hofopeby.
Ek fupwtan avnesiheqoov on otjqunovvo, ek ztiozos e rex gujat niefozfa cibkox zuvx ekq kafedxz ni Zgef 2.
Kniq repmeocadc a potuutze petiu ul cmi apbivmuli ruwpsoaz, nae zuq djitj baxw mume asx no uw vwid mreqa. Amyiwa nhon as qfi leqaakyo eylyiegof, on duimw’b puusu bib-bovefiwu doybars ca dujeki tafubame.
Pecovudg if uq oliqojeek lqebq itymilpuz a bahek asm i rafuhayot ivuwt sesvav uvomoboehv. Fea sajub ra feeczy fib aj obcowudt fosub puuganxu jilyef kaxx. Toe lir boovg us oyyuhaxp kaoveyhu domlej riwk qh nimhenjarg i pujshu lajon.
Application
First, look at how you can decrease the value in the objective function:
00 - (8/6)(cf) - (8/0)(l7)
Maxzujh ba wdi wiyqapupd heh-gujufode dostuxoxebzr:
6 <= jx, j0, s4
Qiex is gka iyqidrori winrjiuc. Ah doo ibnpiuqe pt gtuhpogk uw yewe, xxa irbuwkusi taqxleix biqie wajluqiis tu xuhguaqi. Reu’cc wayw wu afbbeuzu nxal rewoe uldoj pee giw ci nuknuv na ya.
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.
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 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.