day9约束---layout

  • (void)viewDidLoad {
    [super viewDidLoad];

    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor redColor];

    //用Constraints(layout)来布局;哪个视图(view)使用layout布局哪个控件就必须写这句话
    [view setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addSubview:view];

    //****************** 给视图添加约束的四个步骤 ***************************
    //被添加的约束对象的superView
    //第一个参数:表示被添加约束的对象;
    //第二个参数:表示被约束的方向;是一个枚举值;
    /*
    NSLayoutAttributeLeft = 1,
    NSLayoutAttributeRight,
    NSLayoutAttributeTop,
    NSLayoutAttributeBottom,
    NSLayoutAttributeLeading,
    NSLayoutAttributeTrailing,
    NSLayoutAttributeWidth,
    NSLayoutAttributeHeight,
    NSLayoutAttributeCenterX,
    NSLayoutAttributeCenterY,
    */
    //第三个参数: 写零

    //第四个参数:参照的对象
    //第五个参数:与参照对象的方向
    //第六个参数:比例,指的是view的宽和高的比例
    //第七个参数:两个视图的距离
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeLeft relatedBy:0 toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:30]];

//确定y轴
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:0 toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:30]];

//******* 第一种约束方法 ********
//单独给约束对象宽度,是不需要给参照对象的;
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:40]];

//******* 第二种约束方法 *******
//用一个view的宽度来约束另一个view的宽度;约束是相互制约的
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:0 toItem:view attribute:NSLayoutAttributeHeight multiplier:1 constant:0]];



UIView *view1 = [[UIView alloc] init];
view1.backgroundColor = [UIColor blueColor];;
[view1 setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:view1];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeLeft relatedBy:0 toItem:view attribute:NSLayoutAttributeRight multiplier:1 constant:40]];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeCenterY relatedBy:0 toItem:view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeWidth relatedBy:0 toItem:view attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeHeight relatedBy:0 toItem:view attribute:NSLayoutAttributeHeight multiplier:1 constant:0]];

}

你可能感兴趣的:(day9约束---layout)