NSAnimationContext 不会为 NSButton 设置帧大小动画

dro*_*ang 5 macos cocoa animation nsanimationcontext swift

对于某些视图类型(包括)NSAnimationContext.runAnimationGroup(_:_:),按照NSAnimationContext文档中的演示使用动画框架原点大小可以正常工作NSImageView。但是,NSButton除非我在动画添加明确的帧大小更改否则它不会按预期工作

动画帧大小 NSImageView

对于 NSImageView,以下内容按预期工作。它被移动到原点,并调整为 200x200:

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")
}
Run Code Online (Sandbox Code Playgroud)

动画帧大小 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")
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我在最后添加以下代码行,在所有动画代码之后,它会按预期工作!

self.button.frame = NSRect(x: 0, y: 0, width: 200, height: 200)
Run Code Online (Sandbox Code Playgroud)

最终的工作清单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)
Run Code Online (Sandbox Code Playgroud)

我不是在这里看礼物马,但我不明白为什么 NSButton 需要这样做,甚至不明白是什么让它起作用。谁能解释为什么在动画代码使动画工作NSButton 之后显式设置帧?

dro*_*ang 1

我怀疑这与运行时生成的隐式自动布局约束有关。修改框架后,自动布局只是将其恢复到原始大小。

我放弃了原来的方法,转而采用以下方法:

  1. 在 Interface Builder 中创建宽度和/或高度约束。我使用默认优先级 1000(约束是强制性的)。
  2. 创建宽度和/或高度的出口NSLayoutConstraint。这在 IB 中很棘手:我必须双击检查器的测量选项卡中的约束,然后在检查器中打开约束对象。然后您可以选择连接选项卡并连接插座。
  3. 在我的NSViewController子类中,我使用锚点来定义新的高度或宽度:theWidthConstraint.constant = 200然后是self.view.needsUpdateConstraints = true

这种方法更干净,并且与自动布局系统更兼容。此外,它还可以轻松地对新自动布局导致的整个布局更改进行动画处理:

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