UIView 动画自己的高度

UIView animating its own height

我在 UIViewController 中制作了一个 UIView 的简单示例,因此当我点击内部视图时,它会增加和减少其高度。效果很好,但我无法使高度过渡动画化。

这里是视图控制器,后面是视图:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let theView = MyView()
        theView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(theView)
        
        NSLayoutConstraint.activate([
            theView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 50.0),
            theView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant:0.0),
            theView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: 0.0),
            theView.heightAnchor.constraint(equalToConstant: 925)
            ])
    }
}

class MyView: UIView {
    fileprivate var closedChanger = NSLayoutConstraint()
    fileprivate var isOpen = false
    
    init() {
        super.init(frame: CGRect.zero)
        setupView()
    }
    
    fileprivate func setupView() {
        self.backgroundColor = .gray
        
        self.translatesAutoresizingMaskIntoConstraints = true
        closedChanger = self.heightAnchor.constraint(equalToConstant: 150.0)
        NSLayoutConstraint.activate([
            closedChanger // start off with it shorter
        ])
        self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:))))
    }
    
    @objc func handleTap(sender: UITapGestureRecognizer) {
        UIView.animate(withDuration: 1.0, animations: {
            self.closedChanger.constant = self.isOpen ? self.closedChanger.constant - 25 : self.closedChanger.constant + 25
            // self.layoutIfNeeded()
        })
        isOpen.toggle()
    }
}

layoutIfNeeded不影响。是否不允许 UIView 为其自身的高度变化设置动画?

当您说视图不能使自身动画时,您说得对。问题是您需要为包含视图的更改设置动画,因为正在更改的是视图层次结构。

您需要在动画块外部更改约束,然后在动画块中的父视图上调用 layoutIfNeeded

@objc func handleTap(sender: UITapGestureRecognizer) {
    self.closedChanger.constant = self.isOpen ? self.closedChanger.constant - 25 : self.closedChanger.constant + 25
    UIView.animate(withDuration: 1.0, animations: {     
        self.superview?.layoutIfNeeded()
    })
    isOpen.toggle()
}