Swift - constraint animation - incorrect subviews animating

I have extended UIView:

class A: UIView {
     private var _height: NSLayoutConstraint!
     private var _centerLabel: UILabel = {
        let lb = UILabel()
        lb.text = "Some text"
        lb.adjustsFontSizeToFitWidth = true
        lb.textAlignment = .center
        lb.translatesAutoresizingMaskIntoConstraints = false
        return lb
    }()

     func open() {
          self._height.constant = 50
          self.superview?.layoutIfNeeded()
     }

     func close() {
         UIView.animate(withDuration: 1, delay: 1, options: .curveLinear, animations: {
                self._height.constant = 0
                self.superview?.layoutIfNeeded()
            }, completion: nil)
     }

     override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(_centerLabel)

        _height = self.heightAnchor.constraint(equalToConstant: 0)
        NSLayoutConstraint.activate([
            _centerLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16),
            _centerLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16),
            _centerLabel.topAnchor.constraint(lessThanOrEqualTo: self.topAnchor, constant: 16),
            _centerLabel.bottomAnchor.constraint(greaterThanOrEqualTo: self.bottomAnchor, constant: -16),
            _height
        ])
    }
}

MainViewController:

class MainViewController: UIViewController {

    @IBOutlet weak var a: A!

   override func viewDidLoad() {
       super.viewDidLoad()
   }

   @IBAction func open(_ sender: Any) {
       a.open()
   }

   @IBAction func close(_ sender: Any) {
       a.close()
   }

}

If I call close(), instance of UIView A animates correctly, all other constraint attached to it as well. However, content of A (_centerLabel) disappears immediatelly, its height is not animated at all. Why?

1 answer

  • answered 2017-08-12 09:41 Rakesh Patel

    Use As code below

    UIView.animate(withDuration: 0.5) {
    
                self.topconstraint.constant = 0
                self.tblView.layoutIfNeeded()
            }