Learn to love Auto Layout programmatically.docx
《Learn to love Auto Layout programmatically.docx》由会员分享,可在线阅读,更多相关《Learn to love Auto Layout programmatically.docx(24页珍藏版)》请在冰豆网上搜索。
![Learn to love Auto Layout programmatically.docx](https://file1.bdocx.com/fileroot1/2022-12/13/ca13b95e-a8f5-4004-9c75-31c400c75eba/ca13b95e-a8f5-4004-9c75-31c400c75eba1.gif)
LearntoloveAutoLayoutprogrammatically
AutoLayout
May13th,2014
LEARNTOLOVEAUTOLAYOUT…PROGRAMMATICALLY
HiDevs!
Thisarticleiscurrentlyunderreviewsinceitcontainsdeprecatedinformation.
I’mwritinganewupdatedarticleaboutAutoLayoutanditwillbesoononline!
Myapologiesfortheinconvenience,
Yari
LearntoloveAutoLayoutprogrammatically
Thelastmonthswerequiteintense. Nicola andI,havereleasedan iOSAppforaclient thatrightnowisheavilyfeaturedintheItalianAppStore,I’mplanningatriptoJapan(actually,mygirlfriendis…)andI’vestartedanewpersonaliOSproject.
Nonetheless,I’mreadytocontinueonourjourneywithAutoLayout!
InthepreviousarticleIintroducedthetopicwithsomeeasyexamples(please,ifyouarenewtoAutoLayout,readthatbeforeproceeding).
Intro
InthisnewpostIwanttoshowyouhowtouseAutoLayoutprogrammatically.Itmeansthatwearenotgoingtousexiborstoryboards…justcode.
BeforeopeningxCodelet’squicklyintroducethe VisualFormatLanguage(VFL)andthefunctionsneededtomanagethelayout.
WithVFLyoucandefineconstraintsusingasimplesyntax.Forexampleyoucandefinethe width ofanelementusingthisstring:
"H:
[element(100)]"
ortheheightusing:
"V:
[element(100)]"
Thefirstuppercasechartellswhichdimensionyouwanttomodify. H standsforhorizontaland V forVertical.Thenyoudefinetheconstraints(moreaboutthatinthenextexamples).
Constraintsaredefinedbythe NSLayoutConstraint class.YoucanattachnewconstraintstoaviewwithUIView’smethod addConstraint(s):
andremovethemwithremoveConstraint(s):
Let’scode
Download theproject andopenthefileviewController.m.
Thisfilecontainsallthecodeforthistutorialanditisorganisedinsingleautonomousfunctions(withalotofrepeatedcode!
F@*&youDRY-.-).Eachfunctionrepresentsanexample.
Youcanactivatetheexamplesfromthe viewDidLoad function.
Themainviewcontains2subviews:
redViewandyellowView.InthenextexamplesyouaregoingtoplacetheseviewsintotheboundsofthemainviewusingAutoLayoutonly.
Themethods setupViews istheplacewheretheviewsareinitialisedandconfigured:
-(void)setupViews
{
self.redView=[UIViewnew];
self.redView.translatesAutoresizingMaskIntoConstraints=NO;
self.redView.backgroundColor=[UIColorcolorWithRed:
0.95green:
0.47blue:
0.48alpha:
1.0];
self.yellowView=[UIViewnew];
self.yellowView.translatesAutoresizingMaskIntoConstraints=NO;
self.yellowView.backgroundColor=[UIColorcolorWithRed:
1.00green:
0.83blue:
0.58alpha:
1.0];
[self.viewaddSubview:
self.redView];
[self.viewaddSubview:
self.yellowView];
}
Reallyimportant:
whenyouhavetodealwithAutoLayoutprogrammaticallyyoushouldturnoff translatesAutoresizingMaskIntoConstraints .Thisensuresnoconstraintwillbecreatedautomaticallyfortheview,otherwise,anyconstraintyousetislikelytoconflictwithautoresizingconstraints(whenyouaddconstraintsfromIBitautomaticallysetsthatpropertyto NO ).
EX1:
SimpleconstraintswithVFL
Great!
youarereadytogetyourhandsdirty.
Gotofunction example_1 .Thiscodejustaddsasquareinthetopleftcornerofthemainview,likeinthenextimage.
1. First,createadictionarythatassociateskeystoanyviewthatyouaregoingtouseinVFLdefinitions.
NSDictionary*viewsDictionary=@{@"redView":
self.redView};
Inthiscasewe’vemarkedareferencetotheredViewviewusingthekey“redView”.
2. TimetocreatethefirstconstraintswiththemethodconstraintsWithVisualFormat:
options:
metrics:
views:
ofNSLayoutConstraintclass.
ThismethodreturnsanNSArrayofconstraints.DependingontheVFLyoupasstothefunctionitcreatesoneoremoreconstraints.
InthisexampleweshapewidthandheightconstraintsforredViewusingthiscode:
NSArray*constraint_H=[NSLayoutConstraintconstraintsWithVisualFormat:
@"V:
[redView(100)]"options:
0metrics:
nilviews:
viewsDictionary];
NSArray*constraint_V=[NSLayoutConstraintconstraintsWithVisualFormat:
@"H:
[redView(100)]"options:
0metrics:
nilviews:
viewsDictionary];
Let’sstartbyanalysingthevisualformatstrings.
Aspreviouslyshown,VFLusesHorVtodefinetheorientationoftheconstraints.Thenthesquarebracketsencloseareferencetoaviewandtheparenthesescontainsthevaluefortheattributeswearesetting(dependingonVorHwesetwidthorheight).
Weuse“redView”topointouttheredViewviewbecausewehavepreviouslydefinedakeyforitinviewsDictionaryandwepassittothe views:
argumentofthefunctions.
NowthatwehavedefinedconstraintsforthesizeweattachittotheredView:
[self.redViewaddConstraints:
constraint_H];
[self.redViewaddConstraints:
constraint_V];
3. TocorrectlydefinetheconstraintsforaviewyouneedtogivetoAutoLayoutenoughinformationtoobtainsizeandposition.WehavealreadygiveninformationforthesizeofredView,nowlet’splaceitinthemainviewbounds.Again,weusethepreviousfunctionjustchangingthevisualformatstring.
NSArray*constraint_POS_V=[NSLayoutConstraintconstraintsWithVisualFormat:
@"V:
|-30-[redView]"options:
0metrics:
nilviews:
viewsDictionary];
NSArray*constraint_POS_H=[NSLayoutConstraintconstraintsWithVisualFormat:
@"H:
|-20-[redView]"options:
0metrics:
nilviews:
viewsDictionary];
Let’stranslatethefirstVisualformatstringinasimpleEnglishsentence.@”H:
|-30-[redView]”standsfor“RedViewmustmaintainadistanceof30pointsfromtheleftsideofitssuperview”
Whilewritingthestringthisway@”H:
[redView]-30-|”wesaythedistancehastobecalculatedfromtherightsideofthesuperview.
Thepipechar“|”canbereadasareferencetothe“superview”oftheobjectbetweensquarebrackets.
ThesameistruefortheVerticalorientation,thistimeapipeontheleftmeans“top”whileontherightmeans“bottom”side,sowewrite:
NSArray*constraint_POS_V=[NSLayoutConstraintconstraintsWithVisualFormat:
@"V:
|-30-[redView]"options:
0metrics:
nilviews:
viewsDictionary];
andthiscodeisdefiningthattheredViewmustkeepadistanceof30pointsfromthetopsideofitssuperview.
YoucouldalsoletthesystemusedefaultspacingcreatingaVFLstringlikethis:
@"V:
|-[redView]"
Nonumericinfoaregiveninthisstring.iOSwilluseadefaultdistance.Justrememberthatthesyntaxneedsthe“-”toseparatethepipeandtheelement.
Nowweneedtoattachtheselastconstraintstoaviewtoletthemtakeeffect.
Theviewtoreceivethisconstraintsisthe mainview .Attentionthough,wearenotattachingtheconstraintstotheredView.Toeasilyrememberhowtoattachconstraints,justrememberthatitisresponsibilityoftheparentviewtoassignpositiontoitschildren.Sointhiscase,themainviewreceivestheconstraintstoarrangeredViewwithinitsbounds.
[self.viewaddConstraints:
constraint_POS_V];
[self.viewaddConstraints:
constraint_POS_H];
Ifyouareusedtoplaceviewsusingtheframepropertyitcouldtakeawhilegetusedtoit.
Atthispoint,compileandruntoyouobtainthepreviouslyshownresult.
EX2:
SimpleconstraintswithVFLandmultipleviews
FromviewDidLoadcommentexample_1andremovethecommentsfromexample_2function.
Inthisexamplewearedealingwithtwoviewsandwecreateconstraintswhichworkforboth.Hereisthefinalresult:
Step 1 and 2 areidenticaltothepreviousexample.HerewesettheviewsDictionaryanddefinesizeconstraints.ThistimeweneedtoaddinformationfortheyellowViewtoo:
NSArray*yellow_constraint_H=[NSLayoutConstraintconstraintsWithVisualFormat:
@"V:
[yellowView(200)]"options:
0
metrics:
nilviews:
viewsDictionary];
NSArray*yellow_constraint_V=[NSLayoutConstraintconstraintsWithVisualFormat:
@"H:
[yellowView(100)]"options:
0metrics:
nil
views:
viewsDictionary];
[self.yellowViewaddConstraints:
yellow_constraint_H];
[self.yellowViewaddConstraints:
yellow_constraint_V];
3. AsItoldyou,aparentviewhastotakecareofitschildren’spositions.Sowecreateconstraintsforthemainviewtodefinewhereredandyellowviewhavetobedrawn.
Let’sstartbywritingtheHorizontalinformation:
NSArray*constraint_POS_H=[NSLayoutConstraintconstraintsWithVisualFormat:
@"H:
|-20-[redView]-10-[yellowView]"options:
0metrics:
nilviews:
viewsDictionary];
Weareusingthesamefunction,sojustfocusontheVFLstring @”H:
|-20-[redView]-10-[yellowView]“ .Translatingittoplainenglishwe’llendupwithmorethanoneconstraint:
-redViewhasadistanceof20pointsfromtheleftsideofitssuperview
-theleftsideofyellowViewis10pointsdistantfromtherightsideofredView
Doesitmakesense?
Iordertohelpyoureadthesestringsyoushouldkeepinmindthattheyarebasedonreallysimplesequenceswherethemainactorsarethe“|”andtheviewsbetween“[]“.Alltheinformationthatseparatestheactorscreateconstraints.
Andtobuildverticalinformationwewrite:
@"V:
|-30-[redView]-40-[yellowView]"
Thisstringsays
-redViewhasadistanceof30pointsfromthetopsideofitssuperview
-thetopsideofyellowViewis40pointsdistantfromthebottomviewofredView.
Again,weattachtheconstraintstothemainview.
[self.viewaddConstraints:
constraint_POS_V];
[self.viewaddConstraints:
constraint_POS_H];
EX3:
SimpleconstraintswithVFLusingalignmentoptions
Thepreviousexampleplacestheviewsinamessyway.Let’srearrangetheminacleanerlayout.Forexamplewecouldaligntheviewstotheirtopsidesobtainingthisresult:
Achievingthatissurprisinglyeasy!
WejustcallthefunctionsconstraintsWithVisualFormat:
options:
metrics:
views specifyingavaluefortheoptionsparameter.Infactthisparameterstandsforalignment-options(atleastatthemoment).
NSArray*