您的位置:首页 > 移动开发 > IOS开发

iOS-AutoLayout(自动布局代码控制)简单总结

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

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

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

1.- (void)addConstraint:(NSLayoutConstraint *)constraint NS_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.view addSubview:v1];

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

    v2.backgroundColor = [UIColor grayColor];

    v2.translatesAutoresizingMaskIntoConstraints = NO;

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

   

   [self.view addConstraint:[NSLayoutConstraint constraintWithItem:v1

                                                          attribute:NSLayoutAttributeWidth

                                                          relatedBy:NSLayoutRelationEqual

                                                             toItem:self.view

                                                          attribute:NSLayoutAttributeWidth

                    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: