1

I'm facing one issue while updating top constraint dynamically.

I have one subview1 added over viewcontroller1 view in its xib file and i have given topview constraint to subview1 as 65 and created an outlet for it.

Now i have added viewcontroller1 view over viewcontroller2. After adding it i'm trying to update the constant value of the constraint to 108. But its not getting reflected.

In viewcontroller1 i'm doing

self.topErrorViewConstarints.constant = 108

self.view.updateConstraints()

Any idea why its not getting reflected?

Varun Mehta
  • 1,653
  • 3
  • 17
  • 35

3 Answers3

0

You need to layout the view again.

self.view.layoutIfNeeded()
Swinny89
  • 6,860
  • 3
  • 31
  • 52
0

Try this:

self.topErrorViewConstarints.constant = 108
self.view.setNeedsUpdateConstraints()
self.view.layoutIfNeeded()

It should work. If not then you made mistake somewhere else.

mixel
  • 22,724
  • 10
  • 111
  • 154
0

That's not how updateConstraints() supposed to work.

You can, of course, modify any constraints then update layout like this:

self.topErrorViewConstarints.constant = 108
self.view.layoutIfNeeded()

But if you want to implement updateConstraints() you need the following:

// Call when you need to update your custom View
self.view.setNeedsUpdateConstraints()

Then inside the View override the function which will be called automatically by the system:

override func updateConstraints() {
    super.updateConstraints()

    topErrorViewConstarints.constant = currentTopErrorConstraint()
}

So, updateConstraints() is better suited for custom views with inner layout, that you don't want to be modified from outside. Also, it's good when you need to update many constraints at once.

kelin
  • 9,553
  • 6
  • 63
  • 92