- (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;
H:[cancelButton(72)]-12-[acceptButton(50)] canelButton宽72,acceptButton宽50,它们之间间距12
H:[wideView(>=60@700)] wideView宽度大于等于60point,该约束条件优先级为700(优先级最大值为1000,优先级越高的约束越先被满足)
V:[redBox]-[yellowBox(==redBox)] 竖直方向上,先有一个redBox,其下方紧接一个高度等于redBox高度的yellowBox
H:|-10-[Find]-[FindNext]-[FindField(>=20)]-| 水平方向上,Find距离父view左边缘默认间隔宽度,之后是FindNext距离Find间隔默认宽度;再之后是宽度不小于20的FindField,它和FindNext以及父view右边缘的间距都是默认宽度。(竖线“|” 表示superview的边缘)
创建一个字典(内部包含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的宽度相等 }];