Learn to love Auto Layout programmaticallyWord格式文档下载.docx
《Learn to love Auto Layout programmaticallyWord格式文档下载.docx》由会员分享,可在线阅读,更多相关《Learn to love Auto Layout programmaticallyWord格式文档下载.docx(24页珍藏版)》请在冰点文库上搜索。
BeforeopeningxCodelet’squicklyintroducethe
VisualFormatLanguage(VFL)andthefunctionsneededtomanagethelayout.
WithVFLyoucandefineconstraintsusingasimplesyntax.Forexampleyoucandefinethe
width
ofanelementusingthisstring:
"
H:
[element(100)]"
ortheheightusing:
V:
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:
[self.viewaddSubview:
self.redView];
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:
@"
[redView(100)]"
options:
0metrics:
nilviews:
viewsDictionary];
NSArray*constraint_V=[NSLayoutConstraintconstraintsWithVisualFormat:
Let’sstartbyanalysingthevisualformatstrings.
Aspreviouslyshown,VFLusesHorVtodefinetheorientationoftheconstraints.Thenthesquarebracketsencloseareferencetoaviewandtheparenthesescontainsthevaluefortheattributeswearesetting(dependingonVorHwesetwidthorheight).
Weuse“redView”topointouttheredViewviewbecausewehavepreviouslydefinedakeyforitinviewsDictionaryandwepassittothe
argumentofthefunctions.
NowthatwehavedefinedconstraintsforthesizeweattachittotheredView:
[self.redViewaddConstraints:
constraint_H];
constraint_V];
3.
TocorrectlydefinetheconstraintsforaviewyouneedtogivetoAutoLayoutenoughinformationtoobtainsizeandposition.WehavealreadygiveninformationforthesizeofredView,nowlet’splaceitinthemainviewbounds.Again,weusethepreviousfunctionjustchangingthevisualformatstring.
NSArray*constraint_POS_V=[NSLayoutConstraintconstraintsWithVisualFormat:
|-30-[redView]"
NSArray*constraint_POS_H=[NSLayoutConstraintconstraintsWithVisualFormat:
|-20-[redView]"
Let’stranslatethefirstVisualformatstringinasimpleEnglishsentence.@”H:
|-30-[redView]”standsfor“RedViewmustmaintainadistanceof30pointsfromtheleftsideofitssuperview”
Whilewritingthestringthisway@”H:
[redView]-30-|”wesaythedistancehastobecalculatedfromtherightsideofthesuperview.
Thepipechar“|”canbereadasareferencetothe“superview”oftheobjectbetweensquarebrackets.
ThesameistruefortheVerticalorientation,thistimeapipeontheleftmeans“top”whileontherightmeans“bottom”side,sowewrite:
andthiscodeisdefiningthattheredViewmustkeepadistanceof30pointsfromthetopsideofitssuperview.
YoucouldalsoletthesystemusedefaultspacingcreatingaVFLstringlikethis:
|-[redView]"
Nonumericinfoaregiveninthisstring.iOSwilluseadefaultdistance.Justrememberthatthesyntaxneedsthe“-”toseparatethepipeandtheelement.
Nowweneedtoattachtheselastconstraintstoaviewtoletthemtakeeffect.
Theviewtoreceivethisconstraintsisthe
mainview
.Attentionthough,wearenotattachingtheconstraintstotheredView.Toeasilyrememberhowtoattachconstraints,justrememberthatitisresponsibilityoftheparentviewtoassignpositiontoitschildren.Sointhiscase,themainviewreceivestheconstraintstoarrangeredViewwithinitsbounds.
[self.viewaddConstraints:
constraint_POS_V];
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:
[yellowView(200)]"
NSArray*yellow_constraint_V=[NSLayoutConstraintconstraintsWithVisualFormat:
[yellowView(100)]"
nil
views:
[self.yellowViewaddConstraints:
yellow_constraint_H];
yellow_constraint_V];
AsItoldyou,aparentviewhastotakecareofitschildren’spositions.Sowecreateconstraintsforthemainviewtodefinewhereredandyellowviewhavetobedrawn.
Let’sstartbywritingtheHorizontalinformation:
|-20-[redView]-10-[yellowView]"
Weareusingthesamefunction,sojustfocusontheVFLstring
@”H:
|-20-[redView]-10-[yellowView]“
.Translatingittoplainenglishwe’llendupwithmorethanoneconstraint:
-redViewhasadistanceof20pointsfromtheleftsideofitssuperview
-theleftsideofyellowViewis10pointsdistantfromtherightsideofredView
Doesitmakesense?
Iordertohelpyoureadthesestringsyoushouldkeepinmindthattheyarebasedonreallysimplesequenceswherethemainactorsarethe“|”andtheviewsbetween“[]“.Alltheinformationthatseparatestheactorscreateconstraints.
Andtobuildverticalinformationwewrite:
|-30-[redView]-40-[yellowView]"
Thisstringsays
-redViewhasadistanceof30pointsfromthetopsideofitssuperview
-thetopsideofyellowViewis40pointsdistantfromthebottomviewofredView.
Again,weattachtheconstraintstothemainview.
EX3:
SimpleconstraintswithVFLusingalignmentoptions
Thepreviousexampleplacestheviewsinamessyway.Let’srearrangetheminacleanerlayout.Forexamplewecouldaligntheviewstotheirtopsidesobtainingthisresult:
Achievingthatissurprisinglyeasy!
WejustcallthefunctionsconstraintsWithVisualFormat:
views
specifyingavaluefortheoptionsparameter.Infactthisparameterstandsforalignment-options(atleastatthemoment).
NSArray*