使用代码给View添加约束
_scrollContentView = [[UIView alloc] init]; _scrollContentView.backgroundColor = [UIColor redColor]; [_scrollView addSubview:_scrollContentView]; _scrollContentView.translatesAutoresizingMaskIntoConstraints = NO; NSLayoutConstraint * scrollContentLeftCT = [NSLayoutConstraint constraintWithItem:_scrollContentView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:_scrollContentView.superview attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0]; NSLayoutConstraint * scrollContentTopCT = [NSLayoutConstraint constraintWithItem:_scrollContentView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_scrollContentView.superview attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]; NSLayoutConstraint * scrollContentRightCT = [NSLayoutConstraint constraintWithItem:_scrollContentView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:_scrollContentView.superview attribute:NSLayoutAttributeRight multiplier:1.0 constant:0]; NSLayoutConstraint * scrollContentbottomCT = [NSLayoutConstraint constraintWithItem:_scrollContentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:_scrollContentView.superview attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]; NSLayoutConstraint * scrollContentVerticallCT = [NSLayoutConstraint constraintWithItem:_scrollContentView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:_scrollContentView.superview attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]; NSLayoutConstraint * scrollContentWidthCT = [NSLayoutConstraint constraintWithItem:_scrollContentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1.0 constant:WIDTH]; [_scrollContentView.superview addConstraints:@[scrollContentLeftCT,scrollContentTopCT,scrollContentRightCT,scrollContentbottomCT,scrollContentVerticallCT]]; [_scrollContentView.superview.superview addConstraint:scrollContentWidthCT];
用代码写约束很麻烦,而且很容易出错,而且容易显示不出来,原因可能是少了一句话
_scrollContentView.translatesAutoresizingMaskIntoConstraints = NO;
如果写了这句话还不能显示出来,就把superView也添加以下这个属性
关于height,和Width这两个属性,第二个item应该为空,该约束应该添加到自己身上,而不是superView身上
关于bottom这个约束,如果想要与superView的底部有一点空隙,constant需要写成负数