- (void)addConstraint:(NSLayoutConstraint *)constraint;
- (void)addConstraints:(NSArray *)constraints;
view.translatesAutoresizingMaskIntoConstraints = NO;
/*
view1 :要约束的控件
attr1 :约束的类型(做怎样的约束)
relation :与参照控件之间的关系
view2 :参照的控件
attr2 :约束的类型(做怎样的约束)
multiplier :乘数
c :常量
*/
+(id)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;
创建一个字典(内部包含VFL语句中用到的控件)的快捷宏定义 NSDictionaryOfVariableBindings(...)
/*
format :VFL语句
opts :约束类型
metrics :VFL语句中用到的具体数值
views :VFL语句中用到的控件
*/
+ (NSArray *)constraintsWithVisualFormat:(NSString *)format options:(NSLayoutFormatOptions)opts metrics:(NSDictionary *)metrics views:(NSDictionary *)views;
在没有Autolayout之前,UILabel的文字内容总是居中显示,导致顶部和底部会有一大片空缺区域
有Autolayout之后,UILabel的bounds默认会自动包住所有的文字内容,顶部和底部不再会有空缺区域
UILabel实现包裹内容
[UIView animateWithDuration:1.0 animations:
^{
[添加了约束的view layoutIfNeeded];
}];
下载地址: https://github.com/SnapKit/Masonry
//设置约束
- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block;
//如果之前已经有约束,则更新新的约束,如果没有约束,则添加约束
- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *))block;
//将之前的约束全部删除,添加新的约束
- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block;
以下为代码使用实现布局效果:
//添加两个控件
UIView *blueView = [[UIView alloc] init];
blueView.backgroundColor = [UIColor blueColor];
blueView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:blueView];
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
redView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:redView];
//给蓝色View设置约束
[blueView mas_makeConstraints:^(MASConstraintMaker *make) {
14 make.left.equalTo(self.view.mas_left).offset(30);//和父view的左边间距为30;
make.bottom.equalTo(self.view.mas_bottom).offset(-30);//和父view的底部间距为30;
make.right.equalTo(redView.mas_left).offset(-30);//和红色view的间距为30;
make.height.mas_equalTo(50);//蓝色view的高度为50
}];
//给红色View设置约束
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.view.mas_right).offset(-30);//和父view的右边间距为30;
make.bottom.equalTo(blueView.mas_bottom);//和蓝色view的底部对齐
make.height.equalTo(blueView.mas_height);//和蓝色view的高度相等
make.width.equalTo(blueView.mas_width);//和蓝色view的宽度相等
}];
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有