iOS Autolayout

1.Getting started

Understanding Auto Layout
External Changes

  • The user resizes the window (OS X).
  • The user enters or leaves Split View on an iPad (iOS).
  • The device rotates (iOS).
  • The active call and audio recording bars appear or disappear (iOS).
  • You want to support different size classes.
  • You want to support different screen sizes.

Internal Changes

  • The content displayed by the app changes.
  • The app supports internationalization.
  • The app supports Dynamic Type (iOS).

You can programmatically lay out the user interface, you can use autoresizing masks to automate some of the responses to external change, or you can use Auto Layout.
[Additionally, autoresizing masks adapt only to external changes. They do not support internal changes.]

2.Auto Layout Without Constraints

UIStackView/NSStackView
[axis]: defines the stack view’s orientation, either vertical or horizontal.
[orientation] :defines the stack view’s orientation, either vertical or horizontal.
[distribution]:defines the layout of the views along the axis.
[alignment]:defines the layout of the views perpendicular to the stack view’s axis.
[spacing]:defines the space between adjacent views.

3.Anatomy of a Constraint

view_formula_2x.png
  • Item 1. The first item in the equation—in this case, the red view. The item must be either a view or a layout guide
  • Attribute 1. The attribute to be constrained on the first item—in this case, the red view’s leading edge.
  • Relationship. The relationship between the left and right sides. The relationship can have one of three values: equal, greater than or equal, or less than or equal. In this case, the left and right side are equal.
  • Multiplier. The value of attribute 2 is multiplied by this floating point number. In this case, the multiplier is 1.0.
  • Item 2. The second item in the equation—in this case, the blue view. Unlike the first item, this can be left blank.
  • Attribute 2. The attribute to be constrained on the second item—in this case, the blue view’s trailing edge. If the second item is left blank, this must be Not an Attribute.
  • Constant. A constant, floating-point offset—in this case, 8.0. This value is added to the value of attribute 2.
Sample Equations
Equality, Not Assignment
Constraint Inequalities:

As soon as you start using inequalities, the two constraints per view per dimension rule breaks down. You can always replace a single equality relationship with two inequalities.

Constraint Priorities:

1。You can also create optional constraints. All constraints have a priority between 1 and 1000. Constraints with a priority of 1000 are required. All other constraints are optional.
2。When calculating solutions, Auto Layout attempts to satisfy all the constraints in priority order from highest to lowest. If it cannot satisfy an optional constraint, that constraint is skipped and it continues on to the next constraint.
3。Even if an optional constraint cannot be satisfied, it can still influence the layout. If there is any ambiguity in the layout after skipping the constraint, the system selects the solution that comes closest to the constraint. In this way, unsatisfied optional constraints act as a force pulling views towards them.
4碑定。The greater-than-or-equal relationship could be required (priority of 1000), and the less-than-or-equal relationship has a lower priority (priority 250).

Intrinsic Content Size:

UIView and NSView --------> No intrinsic content size.
Sliders --------> Defines only the width (iOS).Defines the width, the height, or both—depending on the slider’s type (OS X).
Labels, buttons, switches, and text fields --------> Defines both the height and the width.
Text views and image views --------> Intrinsic content size can vary.

The intrinsic content size is based on the view’s current content. A label or button’s intrinsic content size is based on the amount of text shown and the font used. For other views, the intrinsic content size is even more complex. For example, an empty image view does not have an intrinsic content size. As soon as you add an image, though, its intrinsic content size is set to the image’s size.
A text view’s intrinsic content size varies depending on the content, on whether or not it has scrolling enabled, and on the other constraints applied to the view. For example, with scrolling enabled, the view does not have an intrinsic content size. With scrolling disabled, by default the view’s intrinsic content size is calculated based on the size of the text without any line wrapping. For example, if there are no returns in the text, it calculates the height and width needed to layout the content as a single line of text. If you add constraints to specify the view’s width, the intrinsic content size defines the height required to display the text given its width.
Auto Layout represents a view’s intrinsic content size using a pair of constraints for each dimension. The content hugging pulls the view inward so that it fits snugly around the content. The compression resistance pushes the view outward so that it does not clip the content.

// Compression Resistance
View.height >= 0.0 * NotAnAttribute + IntrinsicHeight
View.width >= 0.0 * NotAnAttribute + IntrinsicWidth
// Content Hugging
View.height <= 0.0 * NotAnAttribute + IntrinsicHeight
View.width <= 0.0 * NotAnAttribute + IntrinsicWidth
Each of these constraints can have its own priority. By default, views use a 250 priority for their content hugging, and a 750 priority for their compression resistance. Therefore, it’s easier to stretch a view than it is to shrink it.

4.

Fortunately, there are a few methods you can call to help identify ambiguous layouts. All of these methods should be used only for debugging. Set a breakpoint somewhere where you can access the view hierarchy, and then call one of the following methods from the console:

[hasAmbiguousLayout]
. Available for both iOS and OS X. Call this method on a misplaced view. It returns YES
if the view’s frame is ambiguous. Otherwise, it returns NO

[exerciseAmbiguityInLayout]
. Available for both iOS and OS X. Call this method on a view with ambiguous layout. This will toggle the system between the possible valid solutions.

[constraintsAffectingLayoutForAxis:]
. Available for iOS. Call this method on a view. It returns an array of all the constraints affecting that view along the specified axis.

[constraintsAffectingLayoutForOrientation:]
. Available for OS X. Call this method on a view. It returns an array of all the constraints affecting that view along the specified orientation.

[_autolayoutTrace]
. Available as a private method in iOS. Call this method on a view. It returns a string with diagnostic information about the entire view hierarchy containing that view. Ambiguous views are labeled, and so are views that have [translatesAutoresizingMaskIntoConstraints]
set to YES.

You may need to use Objective-C syntax when running these commands in the console. For example, after the breakpoint halts execution, type call [self.myView exerciseAmbiguityInLayout]
into the console window to call the exerciseAmbiguityInLayout
method on the myView
object. Similarly, type po [self.myView autolayoutTrace]
to print out diagnostic information about the view hierarchy containing myView
.

一個(gè)標(biāo)識(shí)出有歧義布局更直觀的方法就是使用exerciseAmbiguityInLayout内斯。這將會(huì)在有效值之間隨機(jī)改變視圖的frame豁陆。然而扭吁,每次調(diào)用這個(gè)方法只會(huì)改變frame一次端圈。所以當(dāng)你啟動(dòng)程序的時(shí)候炫掐,你根本不會(huì)看到改變魁莉。創(chuàng)建一個(gè)遍歷所有視圖層級(jí)的輔助方法是一個(gè)不錯(cuò)的主意,并且讓所有的視圖都有一個(gè)歧義的布局

@implementation UIView (AutoLayoutDebugging)
- (void)exerciseAmiguityInLayoutRepeatedly:(BOOL)recursive {
    #ifdef DEBUG
    if (self.hasAmbiguousLayout) {
        [NSTimer scheduledTimerWithTimeInterval:.5
                                         target:self
                                       selector:@selector(exerciseAmbiguityInLayout)
                                       userInfo:nil
                                        repeats:YES];
    }
    if (recursive) {
        for (UIView *subview in self.subviews) {
            [subview exerciseAmbiguityInLayoutRepeatedly:YES];
        }
    }
    #endif
} @end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末募胃,一起剝皮案震驚了整個(gè)濱河市旗唁,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌痹束,老刑警劉巖检疫,帶你破解...
    沈念sama閱讀 222,590評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異祷嘶,居然都是意外死亡屎媳,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門论巍,熙熙樓的掌柜王于貴愁眉苦臉地迎上來烛谊,“玉大人,你說我怎么就攤上這事嘉汰∩估矗” “怎么了?”我有些...
    開封第一講書人閱讀 169,301評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵郑现,是天一觀的道長。 經(jīng)常有香客問我荧降,道長接箫,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,078評(píng)論 1 300
  • 正文 為了忘掉前任朵诫,我火速辦了婚禮辛友,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己废累,他們只是感情好邓梅,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,082評(píng)論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著邑滨,像睡著了一般日缨。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上掖看,一...
    開封第一講書人閱讀 52,682評(píng)論 1 312
  • 那天匣距,我揣著相機(jī)與錄音,去河邊找鬼哎壳。 笑死毅待,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的归榕。 我是一名探鬼主播尸红,決...
    沈念sama閱讀 41,155評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼刹泄!你這毒婦竟也來了外里?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,098評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤循签,失蹤者是張志新(化名)和其女友劉穎级乐,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體县匠,經(jīng)...
    沈念sama閱讀 46,638評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡风科,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,701評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了乞旦。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片贼穆。...
    茶點(diǎn)故事閱讀 40,852評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖兰粉,靈堂內(nèi)的尸體忽然破棺而出故痊,到底是詐尸還是另有隱情,我是刑警寧澤玖姑,帶...
    沈念sama閱讀 36,520評(píng)論 5 351
  • 正文 年R本政府宣布愕秫,位于F島的核電站,受9級(jí)特大地震影響焰络,放射性物質(zhì)發(fā)生泄漏戴甩。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,181評(píng)論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦凸主、人聲如沸缴川。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽把夸。三九已至而线,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間扎即,已是汗流浹背吞获。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評(píng)論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留谚鄙,地道東北人各拷。 一個(gè)月前我還...
    沈念sama閱讀 49,279評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像闷营,于是被迫代替她去往敵國和親烤黍。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,851評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容