objective-c自动布局纯代码写法

这篇博客探讨了如何在Objective-C中使用纯代码实现自动布局,详细讲解了相关的关键类和方法,帮助开发者更好地理解和应用自动布局技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关键类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]];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值