我已经把这个动画写到CAShapeLayer(pulseLayer(和viewDidLoad()
:
let pulseLayer = CAShapeLayer()
@IBOutlet weak var btnCart: UIButton!
override func viewDidLoad() {
let longpress = UILongPressGestureRecognizer(target: self, action: #selector(CategoryViewController.longPressGestureRecognized(_:)))
tableView.addGestureRecognizer(longpress)
heartBeatAnimation.duration = 0.75
heartBeatAnimation.repeatCount = Float.infinity
heartBeatAnimation.autoreverses = true
heartBeatAnimation.fromValue = 1.0
heartBeatAnimation.toValue = 1.2
heartBeatAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
btnCart.layer.addSublayer(pulseLayer)
}
func addBtnCartLayerWithAnimation() {
let ovalPath = UIBezierPath(arcCenter: CGPoint(x: btnCart.frame.midX, y: btnCart.frame.midY), radius: btnCart.frame.width * 1.5, startAngle: 0*(CGFloat.pi / 180), endAngle: 360*(CGFloat.pi / 180), clockwise: true)
pulseLayer.path = ovalPath.cgPath
pulseLayer.opacity = 0.15
pulseLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
pulseLayer.bounds = ovalPath.cgPath.boundingBox
pulseLayer.add(heartBeatAnimation, forKey: "heartBeatAnimation")
pulseLayer.transform = CATransform3DScale(CATransform3DIdentity, 1.0, 1.0, 1.0)
}
而删除层函数是:
func removeLayer() {
pulseLayer.transform = CATransform3DScale(CATransform3DIdentity, 0.1, 0.1, 0.1)
pulseLayer.removeAllAnimations()
}
问题是当图层的第一个动画来自视图底部时!
viewDidLoad 之后的第一个动画
然后,从中心(定义的锚点(开始对此动画进行任何调用
第一个动画之后的任何动画
谁能告诉我为什么会这样?
我在 tableView 上定义和使用UILongGestureRecognizer
来启动/停止动画的整个类:
func longPressGestureRecognized(_ gestureRecognizer: UIGestureRecognizer) {
let longPress = gestureRecognizer as! UILongPressGestureRecognizer
let state = longPress.state
let locationInView = longPress.location(in: tableView)
let indexPath = tableView.indexPathForRow(at: locationInView)
switch state {
case UIGestureRecognizerState.began:
if indexPath != nil {
addBtnCartLayerWithAnimation()
}
case UIGestureRecognizerState.changed:
// some code here not related to the animation
default:
removeLayer()
}
}
使用独立图层(不是UIView
的后备存储的图层(时,将为每个可动画属性更改添加隐式动画。
您之所以看到此效果,是因为图层正在将其属性从零动画化到您在addBtnCartLayerWithAnimation()
中设置的初始值。
您要做的是在没有动画的情况下设置这些初始值(这需要显式完成(。您可以将更改包装在禁用动画的事务中,如下所示:
CATransaction.begin()
CATransaction.setDisableActions(true)
pulseLayer.path = ovalPath.cgPath
pulseLayer.opacity = 0.15
pulseLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
pulseLayer.bounds = ovalPath.cgPath.boundingBox
pulseLayer.transform = CATransform3DScale(CATransform3DIdentity, 1.0, 1.0, 1.0)
CATransaction.commit()
pulseLayer.add(heartBeatAnimation, forKey: "heartBeatAnimation")