iOS Autolayout 自动布局代码使用规则

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

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

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

在使用自动布局之前要对子视图的布局方式进行调整,用到这个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
                   

你可能感兴趣的:(iOS)