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:1.0 constant:0];

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

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

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

//3.重点地方是,添加到约束到哪里,webview参照view对齐的,所以这些属性是添加到其父控件上面,如果是其属性,比如自己的宽高,则添加到自己上。
[self.view addConstraints:@[left, top, right, bottom]];
//注意:这个方法将被弃用,
- (void)addConstraints:(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 activateConstraints:].
//所以以后统一用这个方法,就不必担心,约束加错对象了。
[NSLayoutConstraint activateConstraints:@[left, top, right, bottom]];

你可能感兴趣的:(objective-c,iOS,objective-c,自动布局,swift)