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,733
  • 3
  • 18
  • 39

4 Answers4

0

You need to layout the view again.

self.view.layoutIfNeeded()
Swinny89
  • 7,273
  • 3
  • 32
  • 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
  • 25,177
  • 13
  • 126
  • 165
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
  • 11,323
  • 6
  • 67
  • 104
0

Problem:

I have faced a similar problem in UiKit code. I created a view programmatically and the add constraint like below:

myView?.heightAnchor.constraint(equalToConstant: oldValue).isActive = true

It worked fine for the first time when the view is created. But need to update the height for some events, so I did like this:

myView?.heightAnchor.constraint(equalToConstant: oldValue).isActive = false
myView?.heightAnchor.constraint(equalToConstant: newValue).isActive = true

But the newValue had no effect, I also try with:

parentOfMyView.layoutIfNeeded()

It was also a failed attempt.

Solution:

I created a global variable to store the constraint:

private var viewHeightAnchor: NSLayoutConstraint?

Then use that when needed:

viewHeightAnchor?.isActive = false
viewHeightAnchor = myView?.heightAnchor.constraint(equalToConstant: 80.0)
viewHeightAnchor?.isActive = true

In this way I also didn't have to call layoutIfNeeded()

SM Abu Taher Asif
  • 2,221
  • 1
  • 12
  • 14