iOS 6 Auto Layout NSLayoutConstraint 界面布局

附上原文地址:http://www.devdiv.com/iOS_iPhone-iOS_6_Auto_Layout_NSLayoutConstraint_%E7%95%8C%E9%9D%A2%E5%B8%83%E5%B1%80-thread-136399-1-1.html(感谢原作者的贡献)


终于ios 6推出了正式版本,同时也随之iphone5的面试,对于ios开发者来说,也许会感觉到一些苦恼。那就是原本开发的程序,需要大量的修改了。为了适应最新的iphone5的屏幕。

在WWDC2012里苹果推出了,Auto Layout的概念。我们可以通过Auto Layout来适应屏幕的改变。

比如我们要做一个如下的界面。



如果按照以前的frame的方式的话,大概代码如下

UIView *myview = [[UIView alloc] init];
myview.backgroundColor = [UIColor greenColor];
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
UIView *blueView = [[UIView alloc] init];
blueView.backgroundColor = [UIColor blueColor];
[myview addSubview:redView];
[myview addSubview:blueView];
redView.frame = CGRectMake(50, 80, 100, 30);
blueView.frame = CGRectMake(180, 80, 100, 30);
self.view = myview;


通过上面的代码我们就能很简单的实现上面的布局效果了,但是使用auto layout的时候我们需要使用如下代码来实现。

view source print ?
UIView *myview = [[UIView alloc] init];
myview.backgroundColor = [UIColor greenColor];
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
UIView *blueView = [[UIView alloc] init];
blueView.backgroundColor = [UIColor blueColor];
[myview addSubview:redView];
[myview addSubview:blueView];
[myview setTranslatesAutoresizingMaskIntoConstraints:NO];
[redView setTranslatesAutoresizingMaskIntoConstraints:NO];
[blueView setTranslatesAutoresizingMaskIntoConstraints:NO];
NSMutableArray *tmpConstraints = [NSMutableArray array];
[tmpConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|-50-[redView(==100)]-30-[blueView(==100)]"options:0 metrics:nil views:NSDictionaryOfVariableBindings(redView,blueView)]];
[tmpConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-30-[redView(==30)]"options:0 metrics:nil views:NSDictionaryOfVariableBindings(redView)]];
[tmpConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-30-[blueView(==redView)]"options:0 metrics:nil views:NSDictionaryOfVariableBindings(blueView,redView)]];
[myview addConstraints:tmpConstraints];
self.view = myview;


最后对于向下兼容的时候我们可以通过

if([myview respondsToSelector:@selector(addConstraints:)]){
//支持auto layout
}else{
//不支持
}

你可能感兴趣的:(iOS 6 Auto Layout NSLayoutConstraint 界面布局)