johnnyjw
johnnyjw

Reputation: 315

NSLayoutConstraint not animating with UIView.animate

I am trying to have a UIView move up on the screen, by changing the constant of a NSLayoutConstriant. The UIView moves but is not animated when moving there.

Initial Constraints

func setUpView(){
    cont = OverlayController()
    let overlay = (cont?.view!)!


    gameView.addSubview(overlay)
    top = overlay.topAnchor.constraint(equalTo: gameView.bottomAnchor, constant: -175)
    centerX = overlay.centerXAnchor.constraint(equalTo: gameView.centerXAnchor)
    width = overlay.widthAnchor.constraint(equalToConstant: gameView.frame.width * 0.7)
    height = overlay.heightAnchor.constraint(equalToConstant: gameView.frame.width * 0.7)
    centerY = overlay.centerYAnchor.constraint(equalTo: gameView.centerYAnchor)
    top?.isActive = true
    centerX?.isActive = true
    width?.isActive = true
    height?.isActive = true

    let swipeListener = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
    swipeListener.direction = .up
    overlay.addGestureRecognizer(swipeListener)
}

Animate Method (Ran on Swipe Up)

func animate(){
    centered = !centered
    cont?.view.layoutIfNeeded()
    self.top?.constant = -500


    UIView.animate(withDuration: 3) {
        self.cont?.view.layoutIfNeeded()
    }
}

How do I get it so that the UIView that is being animated will animate when it moves?

Upvotes: 0

Views: 76

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100541

You need to relayout the superview

func animate(){
    centered = !centered
    self.top?.constant = -500 

    UIView.animate(withDuration: 3) {
        self.view.layoutIfNeeded()
    }
}

Upvotes: 1

Related Questions