萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 動畫新視角:Auto Layout 約束驅動的彈性動畫

核心思想

修改約束常量(constant)+ UIView.animateWithDuration 內調用 layoutIfNeeded = 約束動畫。系統在動畫塊中插值計算佈局屬性,實現平滑過渡。

案例:頂部菜單展開/收合 (iOS Animations by Tutorials)

1. IBOutlet 綁定高度約束

@IBOutlet var menuHeightConstraint: NSLayoutConstraint!

Storyboard 中選擇高度約束 → Connections Inspector → 拖線到 menuHeightConstraint。

2. 按鈕點擊切換動畫

@IBAction func toggleMenu(sender: UIButton) {
    isMenuOpen = !isMenuOpen
    menuHeightConstraint.constant = isMenuOpen ? 200 : 60
    titleLabel.text = isMenuOpen ? "Select Item" : "Packing List"
    
    UIView.animateWithDuration(1.0, delay: 0,
        usingSpringWithDamping: 0.4, initialSpringVelocity: 10,
        options: .CurveEaseIn, animations: {
            self.view.layoutIfNeeded()          // 關鍵:觸發佈局動畫
            let angle = self.isMenuOpen ? CGFloat(M_PI_4) : 0
            self.buttonMenu.transform = CGAffineTransformMakeRotation(angle)
        }, completion: nil)
}

無 IBOutlet 時動態查找約束

for constraint in titleLabel.superview!.constraints {
    if constraint.secondItem as? NSObject == titleLabel
       && constraint.secondAttribute == .CenterX {
        constraint.constant = isMenuOpen ? 100 : 0
        break
    }
}

動態添加約束實現動畫

// 創建圖片視圖並添加 4 個約束
let imgView = UIImageView(image: UIImage(named: "icon"))
imgView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(imgView)

let conX = NSLayoutConstraint(item: imgView, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0)
let conY = NSLayoutConstraint(item: imgView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: imgView.frame.height)
let conW = NSLayoutConstraint(item: imgView, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 0.33, constant: -50)
let conH = NSLayoutConstraint(item: imgView, attribute: .Height, relatedBy: .Equal, toItem: imgView, attribute: .Width, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([conX, conY, conW, conH])

view.layoutIfNeeded()  // 佈局到初始狀態

// 動畫:從底部彈出再彈回
UIView.animateWithDuration(0.8, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0, options: [], animations: {
    conY.constant = -imgView.frame.height/2
    conW.constant = 0
    self.view.layoutIfNeeded()
}, completion: nil)

UIView.animateWithDuration(0.8, delay: 1.0, options: [], animations: {
    conY.constant = imgView.frame.height
    conW.constant = -50
    self.view.layoutIfNeeded()
}, completion: { _ in imgView.removeFromSuperview() })

關鍵點總結

  1. 修改 NSLayoutConstraint.constant
  2. 動畫塊內調用 view.layoutIfNeeded()
  3. 配合 usingSpringWithDamping 實現彈簧感
  4. 動畫完成後清理動態添加的視圖與約束
copyright © 萬盛學電腦網 all rights reserved