将动画添加到子视图时立即调用 CATransaction 完成块
Posted
技术标签:
【中文标题】将动画添加到子视图时立即调用 CATransaction 完成块【英文标题】:CATransaction completion block being called immediately when animation is added to subview 【发布时间】:2019-03-08 23:01:00 【问题描述】:我正在尝试在新添加的 UIImageView 作为子视图上启动动画,但似乎在这种情况下会立即调用完成块,即使在 CATransaction.setCompletionBlock 之后添加了动画
addSubview(imageView)
CATransaction.begin()
let posAnimation = positionAnimation(startPoint: startPoint, endPoint: endPoint, beginTime: beginTime, duration: duration)
let alpAnimation = alphaAnimation(beginTime: beginTime, duration: duration)
CATransaction.setCompletionBlock [weak self] in
print("deleting view")
//imageView.removeFromSuperview()
imageView.layer.add(posAnimation, forKey: nil)
imageView.layer.add(alpAnimation, forKey: nil)
CATransaction.commit()
动画:
private func positionAnimation(startPoint: CGPoint, endPoint:CGPoint, beginTime: CFTimeInterval, duration: CFTimeInterval) -> CAKeyframeAnimation
let positionAnimation = CAKeyframeAnimation(keyPath: "position")
positionAnimation.path = customPath(middlePoint: startPoint, endPoint: endPoint).cgPath
positionAnimation.isRemovedOnCompletion = false
positionAnimation.duration = duration
positionAnimation.beginTime = beginTime
positionAnimation.fillMode = CAMediaTimingFillMode.forwards
return positionAnimation
private func alphaAnimation(beginTime: CFTimeInterval, duration: CFTimeInterval) -> CAKeyframeAnimation
let alphaAnimation = CAKeyframeAnimation(keyPath: "opacity")
alphaAnimation.isRemovedOnCompletion = false
alphaAnimation.fillMode = CAMediaTimingFillMode.forwards
alphaAnimation.values = [1.0, 1.0, 0.0]
alphaAnimation.keyTimes = [0.0,0.5,1.0]
alphaAnimation.duration = duration
alphaAnimation.beginTime = beginTime
return alphaAnimation
知道为什么它不起作用吗?
【问题讨论】:
beginTime
和duration
的值是多少?
持续时间 = 1 和 beginTime = CACurrentMediaTime() + 1
【参考方案1】:
很明显,动画不在渲染树上。即视图没有superView
。或者它的superView
没有superView
。您可能需要检查视图实现功能是否已添加到 window
或 view
某处。
【讨论】:
在viewDidLoad()
之后很久,我将imageView
直接添加到UIViewController
的view
中
所以视图是 UIView 的自定义子类?这个视图的类型是什么,你在哪里实现 addSubView(imageView)以上是关于将动画添加到子视图时立即调用 CATransaction 完成块的主要内容,如果未能解决你的问题,请参考以下文章