Search code examples
iosswiftautolayoutnslayoutconstraint

Safely change NSLayoutConstraint constant value


I have bottom constraint of my UIView object, and i want to change it value. After i did, view did display correctly, but, i see an error log in console;

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x600003cbe670 PSBApp.KeyboardView:0x7fc5f760e010.bottom == UIView:0x7fc5f4503090.bottom + 306   (active)>",
    "<NSLayoutConstraint:0x600003c8cbe0 PSBApp.KeyboardView:0x7fc5f760e010.bottom == UIView:0x7fc5f4503090.bottom - 10   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x600003cbe670 PSBApp.KeyboardView:0x7fc5f760e010.bottom == UIView:0x7fc5f4503090.bottom + 306   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

My code is:

private func setupKeyboard(){
    keyboard.delegate = self
    view.addSubview(keyboard)
    keyboardBottomConstraint = keyboard.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: keyboard.expectedHeight())
    keyboard.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    keyboardBottomConstraint.isActive = true
  }

  private func showKeyboard(){
    let bottomOffset: CGFloat = 10
    keyboardBottomConstraint.constant = -bottomOffset
  }

So, after i setupKeyboard there is no error and no view visible on screen, then, after i call showKeyboard it become visible, but an error appears.


Solution

  • There error / warning message holds the key:

    (
        "<NSLayoutConstraint:0x600003cbe670 PSBApp.KeyboardView:0x7fc5f760e010.bottom == UIView:0x7fc5f4503090.bottom + 306   (active)>",
        "<NSLayoutConstraint:0x600003c8cbe0 PSBApp.KeyboardView:0x7fc5f760e010.bottom == UIView:0x7fc5f4503090.bottom - 10   (active)>"
    )
    

    As you see, KeyboardView has two bottom constraints which cannot both be valid at the same time.

    As per the OP's comments, the setupKeyboard() was inadvertently being called twice, resulting in 2 bottom constraints.