Auto Layout学习1
使用步骤:1.利用NSLayoutConstraint类创建约束对象 2.将约束对象添加到View上
例子:将一个正方形view加入vc中
UIView *centerView = [[UIView alloc]init]; [self.view addSubview:centerView]; centerView.backgroundColor = UIColorFromHex(0xFFEC8B, 1.0); centerView.translatesAutoresizingMaskIntoConstraints = NO;注:UIColorFromHex是我自己定义的宏下面加入约束
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:centerView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:150.0]; [self.view addConstraint:widthConstraint]; NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:centerView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:150]; [self.view addConstraint:heightConstraint]; NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:centerView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:200]; [self.view addConstraint:topConstraint]; NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:centerView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:100]; [self.view addConstraint:leftConstraint];这里简单介绍一下constraintWithItem: 这里是要被约束的对象
attribute: 这里是约束种类(有好多种,下个文章分析吧)
relatedBy: 关系大小
typedef NS_ENUM(NSInteger, NSLayoutRelation) { NSLayoutRelationLessThanOrEqual = -1, NSLayoutRelationEqual = 0, NSLayoutRelationGreaterThanOrEqual = 1,};toItem: 建立约束关系的对象attribute: 约束种类
multiplier:倍数
constant:常量
约束公式: 被约束对象.约束attribute = (关系对象.约束attribute) * 倍数multiplier + 常量constant;
详细属性关系,使用例子下章说吧。。。因为我自己还没搞懂
补充iOS8以后新版约束方法
NSLayoutConstraint *centerX = [NSLayoutConstraint constraintWithItem:centerView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]; centerX.active = YES;
新闻热点
疑难解答