2016-09-21 40 views
2

動畫幀的大小利用NSAnimationContext.runAnimationGroup(_:_:)。然而,由於預期的NSButton,除非我動畫NSAnimationContext不爲NSButton

動畫效果的幀大小後面加一個明確的幀大小變化NSImageView

如預期的NSImageView以下作品這是行不通的。它被移動到原點,並調整爲200×200:

NSAnimationContext.runAnimationGroup({(let context) -> Void in 
    context.duration = 2.0 
    // Get the animator for an NSImageView 
    let a = self.theImage.animator() 
    // Move and resize the NSImageView 
    a.frame = NSRect(x: 0, y: 0, width: 200, height: 200) 
}) { 
    print("Animation done") 
} 

動畫幀大小NSButton

與NSButton執行相同的情況下,該按鈕將移動無法調整

NSAnimationContext.runAnimationGroup({(let context) -> Void in 
    context.duration = 2.0 
    // Get the animator for an NSButton 
    let a = self.button.animator() 
    // Move and resize the NSImageView 
    a.frame = NSRect(x: 0, y: 0, width: 200, height: 200) 
}) { 
    print("Animation done") 
} 

但是,如果我將下面的代碼行添加到最後,所有的動畫後德,它按預期工作!

self.button.frame = NSRect(x: 0, y: 0, width: 200, height: 200) 

NSButton最後,工作列表:

NSAnimationContext.runAnimationGroup({(let context) -> Void in 
    context.duration = 2.0 
    // Get the animator for an NSButton 
    let a = self.button.animator() 
    // Move and resize the NSImageView 
    a.frame = NSRect(x: 0, y: 0, width: 200, height: 200) 
}) { 
    print("Animation done") 
} 
self.button.frame = NSRect(x: 0, y: 0, width: 200, height: 200) 

我不是在尋找一個禮物馬在這裏嘴,但爲什麼這需要NSButton我不明白,或甚至是什麼使其工作。任何人都可以解釋爲什麼明確設定後NSButton的框架動畫代碼使動畫工作?

回答

0

我懷疑這與在運行時生成的隱式自動佈局約束有關。修改完框架後,自動佈局只需將其恢復爲原始大小。

我摒棄,取而代之以下的原始的方法:

  1. 在界面生成器創建的寬度和/或高度的限制。我使用默認優先級1000(約束是強制性的)。
  2. 創建寬度和/或高度的出口NSLayoutConstraint。這在IB中非常棘手:我必須在檢查器的「測量」選項卡中雙擊約束,然後在檢查器中打開約束對象。然後您可以選擇連接選項卡並連接插座。
  3. 在我NSViewController子我用錨來定義新的高度或寬度:由self.view.needsUpdateConstraints = true

theWidthConstraint.constant = 200採取了這一做法是更清潔,並與自動佈局系統兼容。此外,它還可以輕鬆創建新的自動佈局所產生的整個佈局變化的動畫效果:

NSAnimationContext.runAnimationGroup({(let context) -> Void in 
    context.duration = 1.0 
    self.theWidthConstraint.animator().constant = 200 
    // Other constraint modifications can go here 
}) { 
    print("Animation done") 
}