Home > Back-end >  Swift iOS Layout Constraint. Using Constant that is proportional to view height programatically
Swift iOS Layout Constraint. Using Constant that is proportional to view height programatically

Time:10-11

I am laying out a view programatically in Swift for iOS, but struggling to get my constraint quite how I want it. This is what I currently have:

NSLayoutConstraint.activate([
            Logo.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 30),
            Logo.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -30),
            Logo.heightAnchor.constraint(equalToConstant: 55),
            Logo.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 150),
        ])

This is fine on large screens but as the screen gets smaller I want to close the space between the Logo and the label. Currently this is set to a fixed constant of 150. What I would like to do is use a multiplier here that is based on the view height (or something similar) but I can not figure that out. How should I define the constraint to do this? Thanks!

CodePudding user response:

You can try

/* Play with percent as you need also you can check current 
     device type iphone/ipad and set it accordingly  */

let height = UIScreen.main.bounds.height * 0.25 

 logo.topAnchor.constraint(equalTo: label.bottomAnchor, constant: height),
  • Related