標籤:
Auto Layout是什麼
Auto Layout是一個基於constraint(約束)的布局系統,它根據UI元素之間約束關係來調整UI元素的位置和大小。
Auto Layout解決什麼問題
更容易適配不同解析度裝置的螢幕(iPhone 6 Plus, iPhone 6, iPhone 5s/5, iPhone 4s/4)
當裝置旋轉時不需要做額外處理
使用constraint來描述布局邏輯,更利於理解和清晰
如何使用Auto Layout
Auto Layout中約束的類對應是NSLayoutConstraint, 而建立NSLayoutConstraint對象主要有兩種方式,第一種是
| 1234567 |
+ (id)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attribute1 relatedBy:(NSLayoutRelation)relation toItem:(id)view2 attribute:(NSLayoutAttribute)attribute2 multiplier:(CGFloat)multiplier constant:(CGFloat)constant; |
上面方法主要意思是,某個view1的attribute1等於(小於或等於/大於或等於)某個view2的attribute2的multiplier倍加上constant。而attribute主要由表示位置(上/下/左/右)和大小(寬/高)的以下幾個值:
| 1234567891011121314 |
typedef enum: NSInteger { NSLayoutAttributeLeft = 1, NSLayoutAttributeRight, NSLayoutAttributeTop, NSLayoutAttributeBottom, NSLayoutAttributeLeading, NSLayoutAttributeTrailing, NSLayoutAttributeWidth, NSLayoutAttributeHeight, NSLayoutAttributeCenterX, NSLayoutAttributeCenterY, NSLayoutAttributeBaseline, NSLayoutAttributeNotAnAttribute = 0} NSLayoutAttribute; |
簡化一下,使用公式可以表達為:
| 1 |
view1.attribute1 = view2.attribute2 * multiplier + constant |
第二種方式是:
| 1234 |
+ (NSArray *)constraintsWithVisualFormat:(NSString *)format options:(NSLayoutFormatOptions)opts metrics:(NSDictionary *)metrics views:(NSDictionary *)views; |
這種方式主要是採用Visual Format Language(可視化格式語言)來描述約束布局,雖然文法比較簡潔,但是可讀性比較差和容易出錯。
Auto Layout存在問題
雖然Auto Layout在布局view方面是非常強大和靈活,但是建立constraint的文法過於繁雜,引用Masonry一個例子:
| 12345678910111213141516171819202122232425262728293031323334353637 |
UIView *superview = self;UIView *view1 = [[UIView alloc] init];view1.translatesAutoresizingMaskIntoConstraints = NO;view1.backgroundColor = [UIColor greenColor];[superview addSubview:view1];UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);[superview addConstraints:@[ //view1 constraints [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeTop multiplier:1.0 constant:padding.top], [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeLeft multiplier:1.0 constant:padding.left], [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-padding.bottom], [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeRight multiplier:1 constant:-padding.right], ]]; |
如此簡單的一個例子都要編寫這麼多行代碼,想象一下如果建立多個view的constraint時會多麼痛苦啊。另一個方式是採用Visual Format Language (VFL),雖然文法比較簡潔,但是可讀性比較差和容易出錯。
iOS Auto Layout