Vasiliy Korchagin
Vasiliy Korchagin

Reputation: 33

How to set topAnchor constraint relative to the superview height

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

Upvotes: 3

Views: 1253

Answers (2)

vacawama
vacawama

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

Jawad Ali
Jawad Ali

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

Related Questions