AutoLayout自动布局之代码实现

原理:IOS6.0之后,苹果优化了UI界面的布局方式,提出了自动布局的概念,和之前的autoresizing相比功能更强大。子视图基于父视图的自动布局显示。都是父视图去添加对子视图的约束。

在这里主要说的是通过代码对自动布局视图的实现。

代码中一般用到的有两个添加约束的方式:

1.- (void)addConstraint:(NSLayoutConstraint *)constraintNS_AVAILABLE_IOS(6_0);

2.- (void)addConstraints:(NSArray *)constraints NS_AVAILABLE_IOS(6_0);

<</span>

在使用自动布局之前要对子视图的布局方式进行调整,用到这个UIView的属性。

- (BOOL)translatesAutoresizingMaskIntoConstraints NS_AVAILABLE_IOS(6_0);// Default YES

需要将其设置为NO

> 

下面用简单例子说明一下:

   UIView *v1 = [[UIView alloc] initWithFrame:CGRectZero];
  

 v1.translatesAutoresizingMaskIntoConstraints= NO;
    

v1.backgroundColor = [UIColor redColor];
    

[self.viewaddSubview:v1];

   

 UIView *v2 = [[UIView alloc]initWithFrame:CGRectZero];
   

 v2.backgroundColor =[UIColor grayColor];
    

v2.translatesAutoresizingMaskIntoConstraints= NO;
    

[self.view addSubview:v2];//添加两个允许自动布局的子视图

   

   [self.view addConstraint:[NSLayoutConstraintconstraintWithItem:v1
        attribute:NSLayoutAttributeWidth
          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.view
      attribute:NSLayoutAttributeWidth
     multiplier:1.0
          constant:0]];//设置子视图的宽度和父视图的宽度相同

    [self.viewaddConstraint:[NSLayoutConstraint constraintWithItem:v1
     attribute:NSLayoutAttributeHeight
    relatedBy:NSLayoutRelationEqual
                                                             toItem:self.view
         attribute:NSLayoutAttributeHeight
    multiplier:0.5
     constant:0]];//设置子视图的高度是父视图高度的一半

 

   [self.view addConstraints:[NSLayoutConstraintconstraintsWithVisualFormat:@"H:|-0-[v1][v2(==v1)]-0-|" options:0metrics:nil views:views]];//通过addConstraints添加对水平方向上v1的控制--距离父视图左侧距离为0(距离为0的话也可省略)同时将v2的水平方向的宽度和v1设置成相同
    
   

 [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[v1][v2(==v1)]|"options:0 metrics:nil views:views]];/通过addConstraints添加对垂直方向上v1的控制--距离父视图上侧距离为0(距离为0的话也可省略)同时将v2的垂直方向的高度和v1设置成相同
    
  

  [self.view addConstraints:[NSLayoutConstraintconstraintsWithVisualFormat:@"V:|-0-[v1]-0-[v2]-0-|" options:0metrics:nil views:views]];//最后是垂直布局两个子view

这样就可以实现上下两个view,各占一半。旋转屏幕的情况下也会自动处理布局。这样看起来代码多,但是可以适应多种分辨率的屏幕。不排除以后苹果出更大更多分辨率的手机。

 

关于constraintsWithVisualFormat:函数介绍:

constraintsWithVisualFormat:参数为NSString型,指定Contsraint的属性,是垂直方向的限定还是水平方向的限定,参数定义一般如下:

V:|-(>=XXX):表示垂直方向上相对于SuperView大于、等于、小于某个距离

若是要定义水平方向,则将V:改成H:即可

在接着后面-[]中括号里面对当前的View/控件 的高度/宽度进行设定;

options:字典类型的值;这里的值一般在系统定义的一个enum里面选取

metrics:nil;一般为nil ,参数类型为NSDictionary,从外部传入 //衡量标准

views:就是上面所加入到NSDictionary中的绑定的View

在这里要注意的是 AddConstraints  和AddConstraint 之间的区别,一个添加的参数是NSArray,一个是NSLayoutConstraint

使用规则

最后对格式的字符串作一个总结介绍

功能        表达式

水平方向          H:

垂直方向          V:

Views         [view]

SuperView      |

关系         >=,==,<=

空间,间隙       -

优先级        @value


其中:

|: 表示父视图

  -:表示距离

  V:  :表示垂直

  H:  :表示水平

>= :表示视图间距、宽度和高度必须大于或等于某个值

    <=:表示视图间距、宽度和高度必须小宇或等于某个值

    ==:表示视图间距、宽度或者高度必须等于某个值

@  :>=、<=、==  限制   最大为  1000


希望对各位读者有所帮助,如果不妥的地方还望指出.

1.|-[view]-|:  视图处在父视图的左右边缘内

2.|-[view]  :   视图处在父视图的左边缘

3.|[view]   :   视图和父视图左边对齐

4.-[view]-  :  设置视图的宽度高度

5.|-30.0-[view]-30.0-|:  表示离父视图 左右间距  30

6.[view(200.0)]: 表示视图宽度为 200.0

7.|-[view(view1)]-[view1]-|:表示视图宽度一样,并且在父视图左右边缘内

8.V:|-[view(50.0)] : 视图高度为  50

9:V:|-(==padding)-[imageView]->=0-[button]-(==padding)-| : 表示离父视图的距离

为Padding,这两个视图间距必须大于或等于0并且距离底部父视图为 padding。

10:  [wideView(>=60@700)]  :视图的宽度为至少为60 不能超过  700

11: 如果没有声明方向默认为  水平  V:


scrollView使用autoLayout代码案例

UIScrollView *scrollView = [[UIScrollView alloc] init];
UIImageView *imageView = [[UIImageView alloc] init];
[imageView setImage:[UIImage imageNamed:"MyReallyBigImage"]];
[self.view addSubview:scrollView];
[scrollView addSubview:imageView];
 
scrollView.translatesAutoresizingMaskIntoConstraints = NO;//声明使用自动布局,所有子视图也都需要声明
imageView.translatesAutoresizingMaskIntoConstraints = NO;
 

//根据子视图的大小自动得出contentSize
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(scrollView,imageView);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView]|" options:0 metrics: 0 viewsDictionary:viewsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView]|" options:0 metrics: 0 viewsDictionary:viewsDictionary]];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[imageView]|" options:0 metrics: 0 viewsDictionary:viewsDictionary]];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[imageView]|" options:0 metrics: 0 viewsDictionary:viewsDictionary]];



动画

虽然使用Autolayout用了很久,但是都是在XIB和Storyboard上直接拖拽的约束。

对于一些要自定义的view的视图和动画就很难过了,之前一直在网上搜了很多都没有弄明白。最近查了好久总算实现了一个简单的动画。

背景:在xib或storyboard上拖拽一个UIButton,设置约束为水平居中+垂直居中+宽度100+高度100。

实现效果:点击按钮动画将这个按钮移动到,左边距50+上边距50+宽度100+高度100,再点击移动到,左边距150+上边距150+宽度100+高度100,可反复点击。

实现思路:删除在xib上拖拽的约束,如果不删除,控制台会给出约束冲突的提示。新定义约束给予赋值,注意每次赋值新的约束前需要将原有的约束删除,否则还是会提示约束冲突。

  1. //  
  2. //  MyTreeViewController.m  
  3. //  LemonTree2  
  4. //  
  5. //  Created by wdl on 14-10-8.  
  6. //  Copyright (c) 2014年 wdl. All rights reserved.  
  7. //  
  8.   
  9. @interface MyTreeViewController ()  
  10.   
  11. @property(nonatomic,weak)IBOutlet UIButton *buttonAnimation;  
  12. @property(nonatomic,weak)IBOutlet NSLayoutConstraint *cs1;  
  13. @property(nonatomic,weak)IBOutlet NSLayoutConstraint *cs2;  
  14. @property(nonatomic,strongNSMutableArray *csArray;  
  15. @property(nonatomic,assign) BOOL boolButtonAnimation;  
  16.   
  17. @end  
  18.   
  19. @implementation MyTreeViewController  
  20.   
  21. - (void)viewDidLoad {  
  22.     [super viewDidLoad];  
  23.     // Do any additional setup after loading the view from its nib.  
  24.     [self.view setBackgroundColor:[UIColor icebergColor]];  
  25.     self.navigationController.navigationBarHidden = YES;  
  26.     self.csArray = [NSMutableArray arrayWithCapacity:0];  
  27. }  
  28.   
  29. - (void)didReceiveMemoryWarning {  
  30.     [super didReceiveMemoryWarning];  
  31.     // Dispose of any resources that can be recreated.  
  32. }  
  33.   
  34.   
  35. -(IBAction)animationButtonPress:(id)sender{  
  36.     //删除相关的约束  
  37.     [self.view removeConstraint:self.cs1];  
  38.     [self.view removeConstraint:self.cs2];  
  39.     [self.view removeConstraints:self.csArray];  
  40.     [self.csArray removeAllObjects];  
  41.     if (!self.boolButtonAnimation) {  
  42.         [UIView transitionWithView:self.buttonAnimation  
  43.                           duration:1.0  
  44.                            options:UIViewAnimationOptionTransitionFlipFromTop  
  45.                         animations:^{  
  46.                             [self.buttonAnimation setTranslatesAutoresizingMaskIntoConstraints:NO];  
  47.                             NSDictionary *viewsDictionary = @{@"buttonAnimation":self.buttonAnimation};  
  48.                             [self.csArray addObjectsFromArray:[NSLayoutConstraint  
  49.                                                                constraintsWithVisualFormat:@"H:|-50-[buttonAnimation(100)]"  
  50.                                                                options:0  
  51.                                                                metrics:nil  
  52.                                                                views:viewsDictionary]];  
  53.                             [self.csArray addObjectsFromArray:[NSLayoutConstraint  
  54.                                                                constraintsWithVisualFormat:@"V:|-50-[buttonAnimation(100)]"  
  55.                                                                options:0  
  56.                                                                metrics:nil  
  57.                                                                views:viewsDictionary]];  
  58.                             [self.view addConstraints:self.csArray];  
  59.                             [self.buttonAnimation layoutIfNeeded];  
  60.                         } completion:^(BOOL finished) {  
  61.                             self.boolButtonAnimation = YES;  
  62.                         }];  
  63.     } else {  
  64.         [UIView transitionWithView:self.buttonAnimation  
  65.                           duration:1.0  
  66.                            options:UIViewAnimationOptionTransitionFlipFromTop  
  67.                         animations:^{  
  68.                             [self.buttonAnimation setTranslatesAutoresizingMaskIntoConstraints:NO];  
  69.                             NSDictionary *viewsDictionary = @{@"buttonAnimation":self.buttonAnimation};  
  70.                             [self.csArray addObjectsFromArray:[NSLayoutConstraint  
  71.                                                                constraintsWithVisualFormat:@"H:|-150-[buttonAnimation(100)]"  
  72.                                                                options:0  
  73.                                                                metrics:nil  
  74.                                                                views:viewsDictionary]];  
  75.                             [self.csArray addObjectsFromArray:[NSLayoutConstraint  
  76.                                                                constraintsWithVisualFormat:@"V:|-150-[buttonAnimation(100)]"  
  77.                                                                options:0  
  78.                                                                metrics:nil  
  79.                                                                views:viewsDictionary]];  
  80.                             [self.view addConstraints:self.csArray];  
  81.                             [self.buttonAnimation layoutIfNeeded];  
  82.                         } completion:^(BOOL finished) {  
  83.                             self.boolButtonAnimation = NO;  
  84.                         }];  
  85.     }  
  86. }  
  87.   
  88. @end  





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值