Reputation: 473
I created a view like so and I want to position it right under my navigation bar but the constraint I added does nothing and keeps the bar all the way at the top of the view.
_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]];
It has some arbitrary nav title.
Upvotes: 0
Views: 52
Reputation: 6643
If you want to use AutoLayout please set your view's translatesAutoresizingMaskIntoConstraints
NO. Then the Constraint
will work and frame will be useless.
So we should add full constraint(leading, top, trailing, height) like:
_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]];
Moreover on iOS11+ please modify topGuide to self.view.safeAreaLayoutGuide
because in the document we know
Use view.safeAreaLayoutGuide.topAnchor instead of topLayoutGuide.bottomAnchor
Another thing is if you do want a view with 1pt height. You can set its height constraint's constant like 1.0 / [UIScreen mainScreen].scale
Upvotes: 1