본문 바로가기
iOS/이슈

[iOS Issue] UIView.animate에서 constraint 변경 동작 안함

by Sky Titan 2022. 3. 5.
728x90
 

How do I animate constraint changes?

I'm updating an old app with an AdBannerView and when there is no ad, it slides off screen. When there is an ad it slides on the screen. Basic stuff. Old style, I set the frame in an animation bloc...

stackoverflow.com

 

아래와 같이 Constraint의 constant 값을 수정해서 UIView의 크기를 조절하는 애니메이션 함수를 만들었다.

//
//  ViewController.swift
//  Practice
//
//

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var redView: UIView!
    @IBOutlet weak var redViewWidth: NSLayoutConstraint!
    @IBOutlet weak var redViewHeight: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
    }
    
    @IBAction func show(_ sender: Any) {
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveLinear, animations: {
            self.redViewWidth.constant = 240
        }, completion: nil)
    }
    
    @IBAction func close(_ sender: Any) {
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveLinear, animations: {
            self.redViewWidth.constant = 0
        }, completion: nil)
    }
}

하지만 뭔가 내가 예상했던대로 동작하지 않는다.

이 때 animate안에 view.layoutIfNeeded를 호출해주면 정상 동작한다.

 

//
//  ViewController.swift
//  Practice
//

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var redView: UIView!
    @IBOutlet weak var redViewWidth: NSLayoutConstraint!
    @IBOutlet weak var redViewHeight: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
    }
    
    @IBAction func show(_ sender: Any) {
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveLinear, animations: {
            self.redViewWidth.constant = 240
            self.view.layoutIfNeeded()
        }, completion: nil)
    }
    
    @IBAction func close(_ sender: Any) {
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveLinear, animations: {
            self.redViewWidth.constant = 0
            self.view.layoutIfNeeded()
        }, completion: nil)
    }
}

728x90

댓글