关于ios自动布局

原理: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
                    

猜你喜欢

转载自blog.csdn.net/u010209842/article/details/69804336