Search code examples
iosswiftnslayoutconstraint

Value of NSLayoutConstraint constant always return 0 swift 3


I m doing an iOS project using Swift 3, I have a UIPagerViewController and I create a button in the border of one of the ViewControllers inside it. After that I added a constraint to the button like you can see in this image below : enter image description here

The constraint have a value of -33

After that I create the associated IBOutlet to this constraint :

@IBOutlet weak var rightButtonConstraint: NSLayoutConstraint!

I want to get this value programmatically when the ViewController start so I did :

public var defaultRightConstraint: CGFloat = 0.0
    override func viewDidLoad() {
            super.viewDidLoad()
            defaultRightConstraint = rightButtonConstraint.constant // the constraint return 0
            print(" DEFAULT RIGHT CONSTRAINT \(defaultRightConstraint)") // Returns 0 and not -33 why ?
        }

but the value I got is already 0 and not -33 what I m doing wrong ?

Edit :

I tried that without success :

override func viewDidLayoutSubviews() {
        self.view.layoutIfNeeded()
        defaultRightConstraint = rightButtonConstraint.constant
        print(" DEFAULT RIGHT CONSTRAINT \(rightButtonConstraint.constant)")
    }

Solution

  • When viewDidLoad(), the view's subviews is not layout yet. Try to put your code in viewDidLayoutSubviews(), or, before you check the constraint's constant, call view.layoutIfNeeded().