天天看點

objective-c自動布局純代碼寫法

關鍵類

NSLayoutConstraint

//1.首先将需要自動布局的UIView及其子類的translatesAutoresizingMaskIntoConstraints屬性設定為NO。
self.webView.translatesAutoresizingMaskIntoConstraints = NO;

//2.關鍵方法
+(instancetype)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(nullable id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;
//第一個參數item是需要設定自動布局的view,第二個參數attribute是需要設定的位置,第三個參數一般就是NSLayoutRelationEqual,第四個參數toItem是參照的view,第五個參數attribute是參照view的位置,第六個參數multiplier是比例一般是1.0,第七個參數constant是具體的參照值,
NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:self.webView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier: constant:];

NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:self.webView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom multiplier: constant:];

    NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:self.webView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier: constant:];

    NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:self.webView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.bottomLayoutGuide attribute:NSLayoutAttributeTop multiplier: constant:];

//3.重點地方是,添加到限制到哪裡,webview參照view對齊的,是以這些屬性是添加到其父控件上面,如果是其屬性,比如自己的寬高,則添加到自己上。
[self.view addConstraints:@[left, top, right, bottom]];
//注意:這個方法将被棄用,
- (void)addConstraints:(NSArray<__kindof NSLayoutConstraint *> *)constraints NS_AVAILABLE_IOS(_0); // This method will be deprecated in a future release and should be avoided.  Instead use +[NSLayoutConstraint activateConstraints:].
//是以以後統一用這個方法,就不必擔心,限制加錯對象了。
[NSLayoutConstraint activateConstraints:@[left, top, right, bottom]];