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的时候我们需要使用如下代码来实现。

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{
//不支持
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值