【问题标题】:Remove UIBezierPath with animation which added earlier使用先前添加的动画删除 UIBezierPath
【发布时间】:2023-01-19 20:53:36
【问题描述】:

在我的 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)删除带有动画的边框。

如何删除带动画的绘制路径?

【问题讨论】:

    标签: ios swift cabasicanimation


    【解决方案1】:

    假设 allowsMultipleSelection 为真,您可以检查 isSelected 并根据它做不同的事情:

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

    还可以考虑覆盖 isSelected 并将此逻辑放入其 didSet 中,而不是使用 startAnimation 函数。 isSelected 将由 UIKit 自动设置。

    然后,将您的原始代码放在showSelectionAnimation中以显示选择动画。对于取消选择动画,做类似的事情,但反转fromValuetoValue。在动画结束的时候,也要将描边颜色设置回clear,这样一切就回到调用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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 2018-10-30
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多