1. 程式人生 > IOS開發 >iOS 如何動畫改變約束

iOS 如何動畫改變約束

當我們使用 frame 佈局控制元件的時候,如果控制元件的 frame 發生改變時,我們想讓改變產生動畫過渡效果,而不是生硬的直接改變。我們可以使用 UIView 的 animate(withDuration:animations:completion:) 函式來實現,如下面的程式碼:

UIView.animate(withDuration: 0.5) {
     // 改變後的frame
    self.exampleView.frame = CGRect(x: 10,y: 10,width: 100,height: 100)
}
複製程式碼

那當我們使用 AutoLayout 佈局的時候,我們想實現上面的效果該如何寫呢?

通過下面的兩個步驟我們就可以實現:

  • 呼叫 animate(withDuration:animations:completion:) 函式
  • 在函式的閉包新增改變語句
    • 目標控制元件約束的改變
    • 呼叫目標控制元件父檢視的 layoutIfNeeded() 函式

具體例子

宣告全域性變數

private let exampleView = UIView(frame: .zero)
private var topConstraint = NSLayoutConstraint()
複製程式碼

使用 AutoLayout 佈局控制元件

extension ViewController {
    private func setupSubviews
() { exampleView.backgroundColor = .green view.addSubview(exampleView) exampleView.translatesAutoresizingMaskIntoConstraints = false topConstraint = exampleView.topAnchor.constraint(equalTo: view.topAnchor,constant: 100) topConstraint.constant = 100 NSLayoutConstraint.activate([ topConstraint,exampleView.leftAnchor.constraint(equalTo: view.leftAnchor,constant: 100),exampleView.widthAnchor.constraint(equalToConstant: 100),exampleView.heightAnchor.constraint(equalToConstant: 100) ]) let
button = UIButton(type: .custom) button.frame = CGRect(x: 100,y: 400,height: 50) button.backgroundColor = .red button.addTarget(self,action: #selector(buttonAction(_:)),for: .touchUpInside) view.addSubview(button) } } 複製程式碼

動畫改變約束

extension ViewController {
    @objc func buttonAction(_ sender: UIButton) {
        UIView.animate(withDuration: 0.5) {
            // 修改約束
            self.topConstraint.constant = 200
            //呼叫父檢視的 layoutIfNeeded()
            self.view.layoutIfNeeded()
        }
    }
}

複製程式碼

效果圖 - 動畫改變約束

注意事項

  • 在要呼叫目標控制元件的父檢視的 layoutIfNeeded() 函式
  • 注意呼叫的是 layoutIfNeeded() 函式,不是 setNeedsLayout()
  • 參考