UIView 动画自己的高度

时间:2021-04-17 23:48:47

标签: ios animation uiview

我在 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 为自己的高度变化设置动画?

1 个答案:

答案 0 :(得分:1)

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

您需要在动画块之外对约束进行更改,然后在动画块中的superview上调用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()
}