Search code examples
iosswiftanimationconstraintsxcode-storyboard

Swift: removefromSuperview removes constraints


Currently working on some swift program and I've a call to action where I remove a blurview from the superview and at the same time I'm animating 2 buttons.

Everything works like it should but there is one small problem. When I remove the blurview from my superview the constraints on my 2 buttons are being set to 0 on the bottom and animating from that position.

I don't want them to shift to 0. If I don't remove the blurview my animation is working perfectly. I've checked if my button constraints are related to the blurview, but that isn't the case. Because I assumed that it could only reset my constraints when they are relative to the blurview.

My storyboard looks the following:

view
  |->  camera_view
  |->  blur_view
  |->  record_label
  |->  record_button

The code that I'm executing is the following:

@IBAction func recordButton(sender: AnyObject) {
    self.blurView?.removeFromSuperview()
    UIButton.animateWithDuration(0.3, delay: 0.2, options: .CurveEaseOut, animations: {
        var recordButtonFrame = self.recordButton.frame
        var recordLabelFrame = self.recordLabel.frame

        recordButtonFrame.origin.y -= recordButtonFrame.size.height
        recordLabelFrame.origin.y -= recordLabelFrame.size.height

        self.recordButton.frame = recordButtonFrame
        self.recordLabel.frame = recordLabelFrame
        }, completion: { finished in
            print("Button moved")
    })
}

What am I doing wrong?

Kind regards,

Wouter


Solution

  • The problem is that you're animating frames while using constraints. You should be animating constrain changes / constraint constant value changes.

    When you don't remove the view the layout isn't recalculated so your frame animation 'works'. It isn't correct and will get reorganised at some point in the future.

    When you remove the view the layout is recalculated and everything moves around before your animation starts.

    You don't give details of your constraints but it seems likely that you should be animating constraints before removing the view, then removing and ensuring the constraints are all sane on completion.