Setting PureLayout constraints correctly?

800 views Asked by At

Im using PureLayout for my programatic view constraints. I thought I had them setup correctly, size, X and Y addressed. However when I run my code on an SE vs a 7 Plus, the view doesn't align correctly.

Here is a snippet of the code:

 if (shouldSetupConstraints) {
        // bg
        backgroundView.autoPinEdgesToSuperviewEdges()
        // positions
        emailTextField.autoPinEdge(toSuperviewEdge: .top, withInset: 170)
        emailTextField.autoPinEdge(toSuperviewEdge: .left, withInset: 60)
        passwordTextField.autoPinEdge(toSuperviewEdge: .top, withInset: 250)
        passwordTextField.autoPinEdge(toSuperviewEdge: .left, withInset: 60)
        loginButton.autoPinEdge(toSuperviewEdge: .top, withInset: 350)
        loginButton.autoPinEdge(toSuperviewEdge: .left, withInset: 75)
        recoverButton.autoPinEdge(toSuperviewEdge: .top, withInset: 410)
        recoverButton.autoPinEdge(toSuperviewEdge: .left, withInset: 60)
        // confirms setup is done
        shouldSetupConstraints = false
    }

I thought the screen points were the same on retina screens, so why would there be variance with these figures?

2

There are 2 answers

3
Tamás Sengel On

The logical resolution is not the same for an iPhone SE (320x568) and a 7 Plus (414x736).

Instead of positioning every constraint from the top or the left, try using every side of the given superview.

0
Yalcin Ozdemir On

You are just giving the constraints for the super-view edges. You should be using constraints relatively to each other. I am not %100 sure, but this should resolve the screen issue as well.

Here's how you should do:

if (shouldSetupConstraints) {
    // bg
    backgroundView.autoPinEdgesToSuperviewEdges()
    // positions

    emailTextField.autoPinEdge(toSuperviewEdge: .top, withInset: 170)
    emailTextField.autoPinEdge(toSuperviewEdge: .left, withInset: 60)

    passwordTextField.autoPinEdge(.top, to: .bottom, of:  emailTextField, withOffset: 80.0, relation: .equal)
    passwordTextField.autoAlignAxis(.vertical, toSameAxisOf:  emailTextField)

    loginButton.autoPinEdge(.top, to: .bottom, of:  passwordTextField, withOffset: 100.0, relation: .equal)
    loginButton.autoPinEdge(toSuperviewEdge: .left, withInset: 75)

    recoverButton.autoPinEdge(.top, to: .bottom, of:  loginButton, withOffset: 60.0, relation: .equal)
    recoverButton.autoAlignAxis(.vertical, toSameAxisOf:  emailTextField)

    // confirms setup is done
    shouldSetupConstraints = false
}