AutoLayout的使用

在Autolayout之前,有Autoresizing可以作屏幕適配枪汪,但局限性較大涌穆,有些任務根本無法完成。相比之下雀久,Autolayout的功能比Autoresizing強大很多宿稀。Autolayout自iOS 6開始引入。

Autolayout的2個核心概念

  • 參照
  • 約束

1赖捌、在storyboard和xib中使用AutoLayout約束面板添加約束

神圖.png

2祝沸、代碼添加約束

  • 常規(guī)約束

代碼實現(xiàn)Autolayout的注意點

1.禁止將AutoresizingMask默認設置轉(zhuǎn)為約束

View.translatesAutoresizingMaskIntoConstraints = NO;

2.添加約束之前,一定要保證相關控件都已經(jīng)在各自的父控件上
3.不用再給view設置frame

一個NSLayoutConstraint對象就代表一個約束

創(chuàng)建約束對象的常用方法
 /**
     @param view1      要約束的控件
     @param attr1      約束的類型
     @param relation   與參照控制之間的關系
     @param view2      參照的控件
     @param attr2      約束的類型
     @param multiplier 乘數(shù)
     @param c          常量
     */
+(instancetype)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(nullable id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;
自動布局的核心計算公式

obj1.property1 =(obj2.property2 * multiplier)+ constant value

添加約束的規(guī)則
  • 對于兩個同層級view之間的約束關系,添加到它們的父view上
  • 對于兩個不同層級view之間的約束關系罩锐,添加到他們最近的共同父view上
  • 對于有層次關系的兩個view之間的約束關系奉狈,添加到層次較高的父view上
添加約束
- (void)addConstraint:(NSLayoutConstraint *)constraint NS_AVAILABLE_IOS(6_0); 
- (void)addConstraints:(NSArray<__kindof NSLayoutConstraint *> *)constraints NS_AVAILABLE_IOS(6_0); 
移除約束
- (void)removeConstraint:(NSLayoutConstraint *)constraint NS_AVAILABLE_IOS(6_0); // This method will be deprecated in a future release and should be avoided.  Instead set NSLayoutConstraint's active property to NO.
- (void)removeConstraints:(NSArray<__kindof NSLayoutConstraint *> *)constraints NS_AVAILABLE_IOS(6_0); // This method will be deprecated in a future release and should be avoided.  Instead use +[NSLayoutConstraint deactivateConstraints:].
刷新約束
- (void)layoutIfNeeded;
- (void)setNeedsUpdateConstraints NS_AVAILABLE_IOS(6_0);

示例

效果圖.png
效果圖.png
UIView *blueView = [UIView new];
blueView.backgroundColor = [UIColor blueColor];
[self.view addSubview:blueView];
// 禁止將AutoresizingMask默認設置轉(zhuǎn)為約束
blueView.translatesAutoresizingMaskIntoConstraints = NO;

UIView *redView = [UIView new];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
redView.translatesAutoresizingMaskIntoConstraints = NO;

// 藍色視圖
// 高度約束:100
NSLayoutConstraint *heightConstraint1 = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:100];
[blueView addConstraint:heightConstraint1];

// 左邊約束:20
NSLayoutConstraint *leftConstraint1 = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0 constant:20];
[blueView.superview addConstraint:leftConstraint1];

// 右邊約束:20
NSLayoutConstraint *rightConstraint1 = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:-20];
[self.view addConstraint:rightConstraint1];

// 頂部約束:20
NSLayoutConstraint *topConstraint1 = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:20];
[self.view addConstraint:topConstraint1];

// 紅色視圖
// 高度約束:同藍色一樣
NSLayoutConstraint *heightConstraint2 = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:blueView attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0];
[self.view addConstraint:heightConstraint2];
// 寬度約束:藍色一半
NSLayoutConstraint *widthConstraint2 = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:blueView attribute:NSLayoutAttributeWidth multiplier:0.5 constant:0];
[self.view addConstraint:widthConstraint2];

// 頂部約束:距離藍色20
NSLayoutConstraint *topConstraint2 = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:blueView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:20];
[self.view addConstraint:topConstraint2];

// 中心點約束
NSLayoutConstraint *centerXConstraint2 = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
[self.view addConstraint:centerXConstraint2];


  • 可視化格式語言約束VFL(Visual format language)

添加方法
+ (NSArray<__kindof NSLayoutConstraint *> *)constraintsWithVisualFormat:(NSString *)format options:(NSLayoutFormatOptions)opts metrics:(nullable NSDictionary<NSString *,id> *)metrics views:(NSDictionary<NSString *, id> *)views;
一些用法示例
H:[cancelButton(72)]-12-[acceptButton(50)]
canelButton寬72,acceptButton寬50唯欣,它們之間間距12
H:[wideView(>=60@700)]
wideView寬度大于等于60point嘹吨,該約束條件優(yōu)先級為700(優(yōu)先級最大值為1000,優(yōu)先級越高的約束越先被滿足)
V:[redBox][yellowBox(==redBox)]
豎直方向上境氢,先有一個redBox蟀拷,其下方緊接一個高度等于redBox高度的yellowBox
H:|-10-[Find]-[FindNext]-[FindField(>=20)]-|
水平方向上,F(xiàn)ind距離父view左邊緣默認間隔寬度萍聊,之后是FindNext距離Find間隔默認寬度问芬;再之后是寬度不小于20的FindField,它和FindNext以及父view右邊緣的間距都是默認寬度寿桨。(豎線“|” 表示superview的邊緣)
示例
UIView *blueView = [UIView new];
blueView.backgroundColor = [UIColor blueColor];
[self.view addSubview:blueView];
// 禁止將AutoresizingMask默認設置轉(zhuǎn)為約束
blueView.translatesAutoresizingMaskIntoConstraints = NO;

UIView *redView = [UIView new];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
redView.translatesAutoresizingMaskIntoConstraints = NO;

// VFL實現(xiàn)AutoLayout

// 間距
NSNumber *margin = @20;
NSNumber *height = @30;

NSDictionary *views   = NSDictionaryOfVariableBindings(blueView,redView);
NSDictionary *margins = NSDictionaryOfVariableBindings(margin,height);

// 添加水平方向約束
NSString *vfl_h = @"H:|-margin-[blueView]-margin-[redView(==blueView)]-margin-|";
NSArray *constraints_h = [NSLayoutConstraint constraintsWithVisualFormat:vfl_h options:kNilOptions metrics:margins views:views];
[self.view addConstraints:constraints_h];

// 添加垂直方向約束
NSString *vfl_v_b = @"V:|-20-[blueView(height)]";
NSArray *constraints_v_b = [NSLayoutConstraint constraintsWithVisualFormat:vfl_v_b options:kNilOptions metrics:margins views:views];
[self.view addConstraints:constraints_v_b];

NSString *vfl_v_r = @"V:|-20-[redView(height)]";
NSArray *constraints_v_r = [NSLayoutConstraint constraintsWithVisualFormat:vfl_v_r options:kNilOptions metrics:margins views:views];
[self.view addConstraints:constraints_v_r];

上面的示例代碼GitHub

3此衅、使用開源框架Masonry 強烈推薦 ?(????????)??????

Masonry GitHub地址
一位博主的學習地址 講的灰常好

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市亭螟,隨后出現(xiàn)的幾起案子挡鞍,更是在濱河造成了極大的恐慌,老刑警劉巖预烙,帶你破解...
    沈念sama閱讀 212,454評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件墨微,死亡現(xiàn)場離奇詭異,居然都是意外死亡扁掸,警方通過查閱死者的電腦和手機翘县,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,553評論 3 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來谴分,“玉大人锈麸,你說我怎么就攤上這事∥悖” “怎么了忘伞?”我有些...
    開封第一講書人閱讀 157,921評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長沙兰。 經(jīng)常有香客問我虑省,道長,這世上最難降的妖魔是什么僧凰? 我笑而不...
    開封第一講書人閱讀 56,648評論 1 284
  • 正文 為了忘掉前任探颈,我火速辦了婚禮,結(jié)果婚禮上训措,老公的妹妹穿的比我還像新娘伪节。我一直安慰自己光羞,他們只是感情好,可當我...
    茶點故事閱讀 65,770評論 6 386
  • 文/花漫 我一把揭開白布怀大。 她就那樣靜靜地躺著纱兑,像睡著了一般。 火紅的嫁衣襯著肌膚如雪化借。 梳的紋絲不亂的頭發(fā)上潜慎,一...
    開封第一講書人閱讀 49,950評論 1 291
  • 那天,我揣著相機與錄音蓖康,去河邊找鬼铐炫。 笑死,一個胖子當著我的面吹牛蒜焊,可吹牛的內(nèi)容都是我干的倒信。 我是一名探鬼主播,決...
    沈念sama閱讀 39,090評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼泳梆,長吁一口氣:“原來是場噩夢啊……” “哼鳖悠!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起优妙,我...
    開封第一講書人閱讀 37,817評論 0 268
  • 序言:老撾萬榮一對情侶失蹤乘综,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后套硼,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體卡辰,經(jīng)...
    沈念sama閱讀 44,275評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡匿醒,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,592評論 2 327
  • 正文 我和宋清朗相戀三年喘批,在試婚紗的時候發(fā)現(xiàn)自己被綠了库北。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,724評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡抄罕,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出于颖,到底是詐尸還是另有隱情呆贿,我是刑警寧澤,帶...
    沈念sama閱讀 34,409評論 4 333
  • 正文 年R本政府宣布森渐,位于F島的核電站做入,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏同衣。R本人自食惡果不足惜竟块,卻給世界環(huán)境...
    茶點故事閱讀 40,052評論 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望耐齐。 院中可真熱鬧浪秘,春花似錦蒋情、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至夺衍,卻和暖如春狈谊,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背沟沙。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評論 1 266
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留尝胆,地道東北人丧裁。 一個月前我還...
    沈念sama閱讀 46,503評論 2 361
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親贪染。 傳聞我的和親對象是個殘疾皇子缓呛,可洞房花燭夜當晚...
    茶點故事閱讀 43,627評論 2 350

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