swift 删除之前添加动画的UIBezierPath

ldioqlga  于 2023-01-19  发布在  Swift
关注(0)|答案(1)|浏览(170)

在我的UICollectionViewCell中,我通过UIBezierPath添加了一个边框,动画如下所示。

class AnimalSelectionCollectionCell: UICollectionViewCell {
    ...
    let shapeLayer: CAShapeLayer = CAShapeLayer()
    override func layoutSubviews() {
        super.layoutSubviews()
        let path: UIBezierPath = UIBezierPath(
            roundedRect: contentView.bounds.inset(by: UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)),
            byRoundingCorners: .allCorners, cornerRadii: CGSize(width: contentView.bounds.size.width, height: 0.0))
        shapeLayer.path = path.cgPath
    }

    func setData() {
        ...
        shapeLayer.lineWidth = 1.0
        shapeLayer.fillColor = UIColor.clear.cgColor
        contentView.layer.addSublayer(shapeLayer)
    }

    func startAnimation() {
        shapeLayer.strokeColor = AppColors.Text.selectedName.cgColor

        let animation: CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd")
        animation.fromValue = 0.0
        animation.toValue = 1.0
        animation.duration = 0.5

        shapeLayer.add(animation, forKey: "myStroke")
    }
}

在选择UICollectionViewCell时,我调用startAnimation()方法,用动画绘制边框。现在,再次选择时,我想以相反的顺序(即从1.0到0.0)删除带有动画的边框。
如何删除带有动画的绘制路径?

cwxwcias

cwxwcias1#

假设allowsMultipleSelection为真,您可以检查isSelected并根据它执行不同的操作:

func startAnimation() {
    if isSelected {
        showDeselectionAnimation()
    } else {
        showSelectionAnimation()
    }
}

还可以考虑重写isSelected并将此逻辑放在其didSet中,而不是使用startAnimation函数。isSelected将由UIKit自动设置。
然后,将原始代码放入showSelectionAnimation中以显示选择动画。对于取消选择动画,执行类似的操作,但颠倒fromValuetoValue。在动画结束时,还应将笔划颜色设置回透明,以便所有内容都返回到调用showSelectionAnimation之前的状态。

func showDeselectionAnimation() {
    let animation: CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd")
    animation.fromValue = 1.0
    animation.toValue = 0.0
    animation.duration = 0.5
    animation.delegate = self
    shapeLayer.add(animation)
}

...

func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
    shapeLayer.strokeColor = UIColor.clear.cgColor
}

相关问题