准备阶段:
新建storyboard,加入viewController 记为:testViewController
新建testViewController.h,testViewController.m文件
方法一:
1.于testViewController加入控件UIView view2
2.于testViewController.h对view2进行关联
3.添加约束:
//该约束解释:view2的宽度为当前view宽度的2/3
float wdith=self.view.frame.size.width/3;
[self.view2 addConstraint:[NSLayoutConstraint constraintWithItem:
self.view2 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:wdith*2]];
注:
[NSLayoutConstraint constraintWithItem:(id)item
attribute:(NSLayoutAttribute)attribute
relatedBy:(NSLayoutRelation)relation
toItem:(id)otherItem
attribute:(NSLayoutAttribute)otherAttribute
multiplier:(CGFloat)multiplier
constant:(CGFloat)constant]
[NSLayoutConstraint constraintWithItem:view1
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:view2
attribute:NSLayoutAttributeRight
multiplier:1
constant:100]
解释:view1的左侧,在view2的右侧,再多10个点的地方。
附视图的属性和关系的值:
附视图的属性和关系的值:
typedef NS_ENUM(NSInteger, NSLayoutRelation) {
NSLayoutRelationLessThanOrEqual = -1, //小于等于
NSLayoutRelationEqual = 0, //等于
NSLayoutRelationGreaterThanOrEqual = 1, //大于等于
};
typedef NS_ENUM(NSInteger, NSLayoutAttribute) {
NSLayoutAttributeLeft = 1, //左侧
NSLayoutAttributeRight, //右侧
NSLayoutAttributeTop, //上方
NSLayoutAttributeBottom, //下方
NSLayoutAttributeLeading, //首部
NSLayoutAttributeTrailing, //尾部
NSLayoutAttributeWidth, //宽度
NSLayoutAttributeHeight, //高度
NSLayoutAttributeCenterX, //X轴中心
NSLayoutAttributeCenterY, //Y轴中心
NSLayoutAttributeBaseline, //文本底标线
NSLayoutAttributeNotAnAttribute = 0 //没有属性
};