Search code examples
iosswiftuikitconstraintsanchor

Adding negative constraints programmatically


Why do I have to give a negative value to my rigthAnchor constraint of titleLabel to make a 28 margin from the right side of the view. If I just give it the positive value it goes 28 pixels beyond the view.

private func setupLayout() {
    view.addSubview(imageView)
    view.addSubview(titleLabel)

    // *** imageView ***
    if #available(iOS 11.0, *) {
        imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 116).isActive = true
    } else {
        imageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 116).isActive = true
    }
    imageView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    imageView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    imageView.heightAnchor.constraint(equalToConstant: 224).isActive = true

    // *** titleLabel ***
    titleLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 25).isActive = true
    titleLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -28).isActive = true
    titleLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 28).isActive = true
}

Solution

  • Because according to this

    titlelbl.right = view.right - 28
    

    is same as saying

    view.right = titlelbl.right + 28
    

    firstItem.anchor = seconfItem.anchor * multiplier +/- constant

    transformed to

    titleLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -28).isActive = true
    

    OR

    view.rightAnchor.constraint(equalTo: titleLabel.rightAnchor, constant: 28).isActive = true
    

    if you don't like negative values

    Edit:

    Meaning of the constraint when it's -28

    You'are telling auto-layout to set the max x value of titlelbl to be equal to the max x value of the view minus 28

    | - lbl + 28 - |

    but with +28

    | - lbl - | + 28 <<< out of view max x