问题
我有两个视图控制器,它们都包含在各自UINavigationController
的 s 和一个UITabBarController
. 在其中一个视图控制器上,我正在创建气泡效果,在屏幕上绘制气泡并为其位置设置动画。当我使用标签栏移动到另一个视图控制器时会出现问题,这会导致 CPU 达到峰值并保持在 100% 并且气泡继续动画。
代码
气泡的代码封装在一个UIView
子类中。
override func draw(_ rect: CGRect) {
// spawn shapes
for _ in 1 ... 10 { // spawn 75 shapes initially
spawn()
}
}
这drawRect
方法重复调用该spawn
函数以使用气泡填充视图。
fileprivate func spawn() {
let shape = CAShapeLayer()
shape.opacity = 0.0
// create an inital path at the starting position
shape.path = UIBezierPath(arcCenter: CGPoint.zero, radius: 1, startAngle: 0, endAngle: 360 * (CGFloat.pi / 180), clockwise: true).cgPath
shape.position = CGPoint.zero
layer.addSublayer(shape)
// add animation group
CATransaction.begin()
let radiusAnimation = CABasicAnimation(keyPath: "path")
radiusAnimation.fromValue = shape.path
radiusAnimation.toValue = UIBezierPath(arcCenter: center, radius: 100, startAngle: 0, endAngle: 360 * (CGFloat.pi / 180), clockwise: true).cgPath
CATransaction.setCompletionBlock { [unowned self] in
// remove the shape
shape.removeFromSuperlayer()
shape.removeAllAnimations()
// spawn a new shape
self.spawn()
}
let movementAnimation = CABasicAnimation(keyPath: "position")
movementAnimation.fromValue = NSValue(cgPoint: CGPoint.zero)
movementAnimation.toValue = NSValue(cgPoint: CGPoint(x: 100, y: 100))
let animationGroup = CAAnimationGroup()
animationGroup.animations = [radiusAnimation, movementAnimation]
animationGroup.fillMode = kCAFillModeForwards
animationGroup.isRemovedOnCompletion = false
animationGroup.duration = 2.0
shape.add(animationGroup, forKey: "bubble_spawn")
CATransaction.commit()
}
内CATransaction
完成处理程序中,我从超级视图中删除形状并创建一个新形状。函数调用self.spawn()
似乎是问题所在
上viewDidDisappear
包含的视图控制器中,我调用以下内容:
func removeAllAnimationsFromLayer() {
layer.sublayers?.forEach({ (layer) in
layer.removeAllAnimations()
layer.removeFromSuperlayer()
})
CATransaction.setCompletionBlock(nil)
}
我尝试将函数removeAllAnimations
添加到UITabBarControllerDelegate
extension BaseViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
bubblesView.removeAllAnimationsFromLayer()
}
}