NSLayoutConstraint的简单应用

    UIView *topView = [[UIView alloc] init];
    topView.backgroundColor = [UIColor redColor];
    [self.view addSubview:topView];
    topView.translatesAutoresizingMaskIntoConstraints = NO;

    [self.view addConstraints:@[
                                
                                [NSLayoutConstraint constraintWithItem:topView
                                                             attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:10],
                                [NSLayoutConstraint constraintWithItem:topView
                                                             attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-10],
                                [NSLayoutConstraint constraintWithItem:topView
                                                             attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:100],
                                [NSLayoutConstraint constraintWithItem:topView
                                                             attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:20]
                                ]];

 topView在父视图的左边间距10,下边间距-10,宽度为100,高度为20的实现代码

原文地址:https://www.cnblogs.com/salam/p/5065377.html