我创建了一个这样的视图,我想把它放在导航栏的正下方,但是我添加的约束没有做任何事情,并且一直保持在视图顶部的栏。
_navSeparator = [[UIView alloc]initWithFrame: CGRectMake(0, 0,
self.view.frame.size.width, 1)];
_navSeparator.backgroundColor =
[UIColor darkColorTheme];
[self.view addSubview:_navSeparator];
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:_navSeparator attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual toItem:topGuide
attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
它有一些任意的导航标题。
答案 0 :(得分:1)
如果您想使用AutoLayout,请设置您的视图translatesAutoresizingMaskIntoConstraints
NO。那么Constraint
将起作用,框架将毫无用处。
所以我们应该添加完整约束(leading,top,trailing,height),如:
_navSeparator = [[UIView alloc] init];
_navSeparator.translatesAutoresizingMaskIntoConstraints = NO;
_navSeparator.backgroundColor =
[UIColor blackColor];
[self.view addSubview:_navSeparator];
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:_navSeparator attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual toItem:self.view.safeAreaLayoutGuide
attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:_navSeparator attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual toItem:self.view
attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:_navSeparator attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual toItem:self.view
attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
[_navSeparator addConstraint:[NSLayoutConstraint
constraintWithItem:_navSeparator attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual toItem:nil
attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:1.0]];
此外,在iOS11 +上,请将topGuide修改为self.view.safeAreaLayoutGuide
,因为在我们知道的文档中
使用view.safeAreaLayoutGuide.topAnchor而不是 topLayoutGuide.bottomAnchor
另一件事是你想要一个高度为1pt的视图。您可以设置其高度约束的常量,如1.0 / [UIScreen mainScreen].scale