我使用三个函数来结合平移手势识别器来处理动画。
private var runningAnimations = [UIViewPropertyAnimator]()
private func startInteractiveTransition(gestureRecognizer: UIPanGestureRecognizer, state: ForegroundState, duration: TimeInterval) {
if runningAnimations.isEmpty {
animateTransitionIfNeeded(gestureRecognizer: gestureRecognizer, state: state, duration: duration)
}
for animator in runningAnimations {
animator.pauseAnimation()
animationProgressWhenInterrupted = animator.fractionComplete
}
}
private func animateTransitionIfNeeded(gestureRecognizer: UIPanGestureRecognizer, state: ForegroundState, duration: TimeInterval) {
guard runningAnimations.isEmpty else {
return
}
let frameAnimator = UIViewPropertyAnimator(duration: duration, dampingRatio: 1) {
switch state {
case .expanded:
// change frame
case .collapsed:
// change frame
}
}
frameAnimator.isReversed = false
frameAnimator.addCompletion { _ in
print("remove all animations")
self.runningAnimations.removeAll()
}
self.runningAnimations.append(frameAnimator)
for animator in runningAnimations {
animator.startAnimation()
}
}
private func updateInteractiveTransition(gestureRecognizer: UIPanGestureRecognizer, fractionComplete: CGFloat) {
if runningAnimations.isEmpty {
print("empty")
}
for animator in runningAnimations {
animator.fractionComplete = fractionComplete + animationProgressWhenInterrupted
}
}
所以我相信这可能与swift处理内存的方式有关,或者与UIViewAnimating如何完成动画有关。
有什么建议吗?
发布于 2018-07-25 05:08:35
我开始意识到我遇到的问题是UIViewPropertyAnimator在反转时如何处理布局约束。我在网上或官方文档中找不到太多关于它的细节,但我确实发现这一点很有帮助。
动画只是将视图动画化为新的帧。但是,无论是否反转,无论是否反转动画制作程序,新约束都仍然有效。因此,在动画师完成后,如果稍后自动布局再次布局视图,我希望视图进入当前活动约束设置的位置。简单地说:动画师为帧变化设置动画,而不是约束本身。这意味着反转动画反转帧,但它不反转约束-一旦自动布局执行另一个布局周期,它们将再次应用。
与正常情况一样,您可以设置约束并调用view.layoutIfNeeded()
animator = UIViewPropertyAnimator(duration: duration, dampingRatio: 1) {
[unowned self] in
switch state {
case .expanded:
self.constraintA.isActive = false
self.constraintB.isActive = true
self.view.layoutIfNeeded()
case .collapsed:
self.constraintB.isActive = false
self.constraintA.isActive = true
self.view.layoutIfNeeded()
}
}
现在,由于我们的动画制作人员具有反转的能力,我们添加了一个完成处理程序,以确保通过使用完成位置在完成时激活正确的约束。
animator.addCompletion { [weak self] (position) in
if position == .start {
switch state {
case .collapsed:
self?.constraintA.isActive = false
self?.constraintB.isActive = true
self?.view.layoutIfNeeded()
case .expanded:
self?.constraintA.isActive = false
self?.constraintB.isActive = true
self?.view.layoutIfNeeded()
}
}
}
发布于 2019-10-30 05:09:15
这是文档的关键部分。您可以正确设置动画:帧、中心、alpha和变换,因此无法正确设置NSConstraints的动画。
您应该修改addAnimations
块内的视图框架
https://stackoverflow.com/questions/51485746
复制相似问题