Learn to love Auto Layout programmatically.docx

上传人:b****3 文档编号:5222465 上传时间:2022-12-14 格式:DOCX 页数:24 大小:569.21KB
下载 相关 举报
Learn to love Auto Layout programmatically.docx_第1页
第1页 / 共24页
Learn to love Auto Layout programmatically.docx_第2页
第2页 / 共24页
Learn to love Auto Layout programmatically.docx_第3页
第3页 / 共24页
Learn to love Auto Layout programmatically.docx_第4页
第4页 / 共24页
Learn to love Auto Layout programmatically.docx_第5页
第5页 / 共24页
点击查看更多>>
下载资源
资源描述

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

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*

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 解决方案 > 学习计划

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1