这是一个简单的测试,所有代码如下,为什么当宽度更改为30时lblA没有动画?但是当宽度更改为300时它具有动画。
import UIKit
class ViewController: UIViewController {
let lblA = UILabel()
var lblAWidthConstraint: NSLayoutConstraint?
var tag = false
// let lblB = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.lblA.backgroundColor = .red
self.view.addSubview(self.lblA)
self.lblA.translatesAutoresizingMaskIntoConstraints = false
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[v]"
, options: []
, metrics: nil
, views: ["v" : self.lblA]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v]|"
, options: []
, metrics: nil
, views: ["v" : self.lblA]))
let widthConstraint = self.lblA.widthAnchor.constraint(equalToConstant: 30)
widthConstraint.isActive = true
self.lblAWidthConstraint = widthConstraint
//
let tap = UITapGestureRecognizer(target: self, action: #selector(tapView))
self.view.addGestureRecognizer(tap)
}
@objc func tapView() {
tag = !tag
self.lblAWidthConstraint?.constant = tag ? 300 : 30
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}
}
[UPDATE]最后,我发现了这一点:Animating Frame of UILabel smoothly