首页 > 代码库 > 代码实现AutoLayout

代码实现AutoLayout

1、iOS布局格式语言(Visual Format Language)

 
常见符号  
H:水平布局(默认)
V:垂直布局
|superView的边界,水平布局模式下,放在左边是左边界,放在右边是右边界;处置布局模式下,则相应的为上边界和下边界
- 标准间隔距离
-N-长度为N像素点的间隔距离
[view]被约束的view
==,>=,<=用于限制view的长宽
@N约束生效的优先级,最高是1000,等级高的优先考虑

例如:代码一

    [NSLayoutConstraint constraintsWithVisualFormat:@"|-50-[redView(==100)]-30-[blueView(==100)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(redView,blueView)];

其中,@"|-50-[redView(==100)]-30-[blueView(==100)]"的意思理解为:redView宽度为100,距离superView的左边界为50,与blueView的间距始终保持30,blueView 的宽度为100

 

2、实例代码:代码二

//头文件
@interface
DemoViewController () { UILabel * _labelA; UILabel * _labelB;}@end
//viewDidLoad方法- (void)viewDidLoad{ [super viewDidLoad]; _labelA = [[UILabel alloc] init]; _labelA.translatesAutoresizingMaskIntoConstraints = NO; _labelA.backgroundColor = [UIColor blueColor]; _labelA.numberOfLines = 0; _labelA.text = @"AAAAAAAAAAAAAAAAAAAAA"; [self.view addSubview:_labelA]; _labelB = [[UILabel alloc] init]; _labelB.translatesAutoresizingMaskIntoConstraints = NO; _labelB.backgroundColor = [UIColor yellowColor]; _labelB.numberOfLines = 0; _labelB.text = @"BBBBBBBBBBBBBBBBBBBBB"; [self.view addSubview:_labelB]; NSDictionary * views = @{@"labelA":_labelA,@"labelB":_labelB}; NSDictionary * metrics = @{@"top":@20,@"left":@20,@"bottom":@20,@"right":@20,@"width":@200,@"height":@50,@"vPadding":@30,@"hPadding":@30}; NSString * vLayoutString = @"V:|-top-[labelA(==height)]-vPadding-[labelB(>=height)]"; NSArray * vLayoutArray = [NSLayoutConstraint constraintsWithVisualFormat:vLayoutString options:0 metrics:metrics views:views]; NSString * hLayoutString = @"H:|-left-[labelA(==width)]-hPadding-[labelB(<=width)]"; NSArray * hLayoutArray = [NSLayoutConstraint constraintsWithVisualFormat:hLayoutString options:0 metrics:metrics views:views]; [self.view addConstraints:vLayoutArray]; [self.view addConstraints:hLayoutArray];}

 

注意:

  a、代码一中和代码二中,constraintsWithVisualFormat: options:metrics:views:方法,传入的参数略有差异,尤其需要注意的是views参数,代码一传入的views参数为options:metrics:views:NSDictionaryOfVariableBindings(redView,blueView)],这样会自动生成类似@{@"redView":redView,@"blueView":blueView}的字典,即字典的key和value的值,表面上看起来是“一样的”,如@“redView”:redView,而代码二中直接传入了一个自定义的字典,这样key和value不用保持“一致”

  b、关于layoutString,如 @"V:|-top-[labelA(==height)]-vPadding-[labelB(>=height)]",其中的labelA和labelB就是views参数中的key

  c、关于constraintsWithVisualFormat: options:metrics:views:方法,其注释如下:

/* by default, the autoresizing mask on a view gives rise to constraints that fully determine the view‘s position.  Any constraints you set on the view are likely to conflict with autoresizing constraints, so you must turn off this property first. IB will turn it off for you. */- (BOOL)translatesAutoresizingMaskIntoConstraints NS_AVAILABLE_IOS(6_0); // Default YES