IOS手动添加的View 在代码中使用(自动布局)autoLayout

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIButton *btnTest = [UIButton buttonWithType:UIButtonTypeCustom];//不需要去刻意指定x,y的坐标,可以用CGRectZero
    btnTest.backgroundColor = [UIColor redColor];
    btnTest.layer.borderColor = [UIColor yellowColor].CGColor;
    btnTest.layer.borderWidth = 2.0;
    [self.view addSubview:btnTest];
    
    
    [btnTest setTranslatesAutoresizingMaskIntoConstraints:NO];//将使用AutoLayout的方式布局
    //btnTest顶部相对于self.view的顶部距离为100
    NSLayoutConstraint *constraintTop = [NSLayoutConstraint constraintWithItem:btnTest attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:100];
    //btnTest左侧相对于self.view的左侧距离为100
    NSLayoutConstraint *constraintLeft = [NSLayoutConstraint constraintWithItem:btnTest  attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:100];
    //btnTest右侧相对于self.view的右侧距离为100
    NSLayoutConstraint *constraintRight = [NSLayoutConstraint constraintWithItem:self.view  attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:btnTest attribute:NSLayoutAttributeRight multiplier:1.0 constant:100];
    //btnTest底部相对于self.view的底部距离为100
    NSLayoutConstraint *constraintBottom = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:btnTest attribute:NSLayoutAttributeBottom multiplier:1.0 constant:100];
    //水平居中
    NSLayoutConstraint *constraintXCenter = [NSLayoutConstraint constraintWithItem:btnTest attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:00.0f];
    //垂直居中
     NSLayoutConstraint *constraintYCenter = [NSLayoutConstraint constraintWithItem:btnTest attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:00.0f];
    
    //将约束添加到父视图中
    [self.view addConstraint:constraintTop];
    [self.view addConstraint:constraintLeft];
    [self.view addConstraint:constraintRight];
    [self.view addConstraint:constraintBottom];
    [self.view addConstraint:constraintXCenter];
    [self.view addConstraint:constraintYCenter];
    
}

  

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。