Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 573
Vasiliy Korchagin Avatar asked Jan 17 '26 23:01

Vasiliy Korchagin


1 Answers

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
like image 92
vacawama Avatar answered Jan 20 '26 15:01

vacawama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!