来自:http://www.devdiv.com/iOS_6_Auto_Layout_NSLayoutConstraint_界面布局-weblog-227936-13173.html
终于ios 6推出了正式版本,同时也随之iphone5的面试,对于ios开发者来说,也许会感觉到一些苦恼。那就是原本开发的程序,需要大量的修改了。为了适应最新的iphone5的屏幕。
在WWDC2012里苹果推出了,Auto Layout的概念。我们可以通过Auto Layout来适应屏幕的改变。
比如我们要做一个如下的界面。
如果按照以前的frame的方式的话,大概代码如下
[代码]c#/cpp/oc代码:
01 |
UIView *myview = [[UIView alloc] init]; |
02 |
myview.backgroundColor = [UIColor greenColor]; |
03 |
UIView *redView = [[UIView alloc] init]; |
04 |
redView.backgroundColor = [UIColor redColor]; |
05 |
UIView *blueView = [[UIView alloc] init]; |
06 |
blueView.backgroundColor = [UIColor blueColor]; |
07 |
[myview addSubview:redView]; |
08 |
[myview addSubview:blueView]; |
09 |
redView.frame = CGRectMake(50, 80, 100, 30); |
10 |
blueView.frame = CGRectMake(180, 80, 100, 30); |
通过上面的代码我们就能很简单的实现上面的布局效果了,但是使用auto layout的时候我们需要使用如下代码来实现。
[代码]c#/cpp/oc代码:
01 |
UIView *myview = [[UIView alloc] init]; |
03 |
myview.backgroundColor = [UIColor greenColor]; |
05 |
UIView *redView = [[UIView alloc] init]; |
07 |
redView.backgroundColor = [UIColor redColor]; |
09 |
UIView *blueView = [[UIView alloc] init]; |
11 |
blueView.backgroundColor = [UIColor blueColor]; |
13 |
[myview addSubview:redView]; |
15 |
[myview addSubview:blueView]; |
17 |
[myview setTranslatesAutoresizingMaskIntoConstraints:NO]; |
19 |
[redView setTranslatesAutoresizingMaskIntoConstraints:NO]; |
21 |
[blueView setTranslatesAutoresizingMaskIntoConstraints:NO]; |
23 |
NSMutableArray *tmpConstraints = [NSMutableArray array]; |
25 |
[tmpConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat: @"|-50-[redView(==100)]-30-[blueView(==100)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(redView,blueView)]]; |
27 |
[tmpConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat: @"V:|-30-[redView(==30)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(redView)]]; |
29 |
[tmpConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat: @"V:|-30-[blueView(==redView)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(blueView,redView)]]; |
31 |
[myview addConstraints:tmpConstraints]; |
最后对于向下兼容的时候我们可以通过
[代码]c#/cpp/oc代码:
1 |
if ([myview respondsToSelector:@selector(addConstraints:)]){ |