Reputation: 33
I have two views: toastView
and view
. toastView
is subview of view
.
I want to position toastView
on the y axis by 80% of view
height.
How can I do this using constants in the code?
I assumed that there is a method like:
[toastView.topAnchor constraintEqualToAnchor:view.heightAnchor multiplier:0.8].active = YES;
but i can't mixing NSLayoutDimension
(width and height) and NSLayoutYAxisAnchor
(X and Y)
This is how it looks in the design:
Upvotes: 3
Views: 1253
Reputation: 154583
The trick here is to set the top of toastView
equal to the bottom of self.view
with a multiplier of 0.8
:
Objective-C:
[NSLayoutConstraint constraintWithItem: toastView attribute: NSLayoutAttributeTop
relatedBy: NSLayoutRelationEqual toItem: self.view
attribute: NSLayoutAttributeBottom multiplier: 0.8 constant: 0].active = YES;
Swift:
NSLayoutConstraint(item: toastView, attribute: .top, relatedBy: .equal,
toItem: self.view, attribute: .bottom, multiplier: 0.8, constant: 0).isActive = true
Upvotes: 6
Reputation: 14397
You can do it like this in swift
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let yConstraint = NSLayoutConstraint(item: toastView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: view.bounds.height * 0.8 )
NSLayoutConstraint.activateConstraints([yConstraint])
}
Objective c
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
NSLayoutConstraint *topAnchorConstraint = [NSLayoutConstraint constraintWithItem:toastView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeTop multiplier:1 constant:(view.bounds.size.height * 0.8)];
[self.view addConstraint:topAnchorConstraint];
}
Upvotes: 0