3

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:

scheme of how it looks on the design

vacawama
  • 150,663
  • 30
  • 266
  • 294

2 Answers2

5

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
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • Thanks, 1 question, is this method an old way to do NSLayout constraint? It takes more code but could be used for relative topAnchor. I found there is no `xxx.topAnchor.constraint(equalTo: holder.bottomAnchor, multiplier: 0.8)` such method when dealing with topAnchor. – Zhou Haibo May 30 '21 at 06:02
  • @ChuckZHB, using NSLayoutContraint is an older and more complete syntax. In this case, using the anchor style syntax doesn't give you access to the ability to set the .top of one item equal to the .bottom of another with a multiplier. – vacawama May 31 '21 at 15:33
  • Ok, so it is the same to what I think, though I didn't confirm it before. Also I google it, that says NSLayout constraint is the raw API. Thanks, I learn a new thing. – Zhou Haibo May 31 '21 at 16:02
0

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];
}
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49