21

斯威夫特 3、iOS 10、macOS 10.12.4

我正在构建一个在 iOS 和 Mac 上运行的应用程序。在 iOS 端,我已经成功地为一个UIView. 当用户点击某物时,会出现一个弹出窗口并动画到位。这是我在点击事件中的代码:

self.popupConstraintX.constant = x
self.popupConstraintY.constant = y

UIView.animate(withDuration: 0.25 , delay: 0.0, options: .curveLinear, animations: {
  self.graphPopup.alpha = 1.0
  self.layoutIfNeeded()

}, completion:nil)

在这种情况下,self指的UITableViewCell是持有graphPopup.

我在 Mac 端构建了相同的东西,但我正在尝试graphPopup为现在的NSView. 这是我到目前为止在点击事件中的内容:

self.popupConstraintX.constant = x
self.popupConstraintY.constant = y

self.view.layoutSubtreeIfNeeded()

NSAnimationContext.runAnimationGroup({_ in
  self.graphPopup.alphaValue = 1.0
  
  //Indicate the duration of the animation
  NSAnimationContext.current().duration = 0.25
  NSAnimationContext.current().allowsImplicitAnimation = true
  self.view.updateConstraints()
  self.view.layoutSubtreeIfNeeded()
  
}, completionHandler:nil)

这里self指的是包含NSViewController. 没有任何东西可以激活-不是位置或alpha. graphPopup它只是出现又消失,就像 1985 年在 Atari 上一样。

知道我的NSView动画做错了什么吗?


更新

为了后代,这里是 BJ 建议的工作代码(稍作调整以使用隐式动画上下文):

self.popupConstraintX.constant = x
self.popupConstraintY.constant = y

NSAnimationContext.runAnimationGroup({context in
  context.duration = 0.25
  context.allowsImplicitAnimation = true
  
  self.graphPopup.alphaValue = 1.0
  self.view.layoutSubtreeIfNeeded()
  
}, completionHandler:nil)
4

2 回答 2

15

的修改alphaValue发生在您打开隐式动画之前,因此不会对 alpha 进行动画处理。我不清楚这是否是故意的。

视图没有对popupConstraints 给出的位置进行动画处理,因为您实际上并没有在动画块内做任何会导致视图框架发生变化的事情。为了触发一个隐式动画,你不仅要更新约束;您还必须确保frame动画块内的视图更改。如果您使用的是 AutoLayout,这通常是通过调用layoutSubtreeIfNeeded.

但是,因为您更新了约束并layoutSubtreeIfNeeded()在动画块之前调用,所以在块内没有其他需要进行的帧更改(除非发生了一些updateConstraints()您没有向我们展示的事情。)

您应该删除对 的第一次调用layoutSubtreeIfNeeded(),或者如果仍然需要,请将其放在popupConstraint修改之上。然后,当您layoutSubtreeIfNeeded()在动画块中调用时,将根据这些更改的约束设置一个新帧,您应该会看到动画正在发生。

于 2017-05-10T21:56:57.990 回答
5

斯威夫特 5

animator()是关键。

你可以简单地这样做:

 NSAnimationContext.runAnimationGroup({ context in

    //Indicate the duration of the animation
    context.duration = 0.25
    self.popupConstraintX.animator().constant = x
    self.popupConstraintY.animator().constant = y
    self.graphPopup.animator().alphaValue = 1.0
   
   }, completionHandler:nil)
于 2020-07-17T13:06:35.193 回答