【问题标题】:Get UIVIew from CAAnimation从 CAAnimation 获取 UIVIew
【发布时间】:2019-03-13 15:31:54
【问题描述】:

我正在尝试从CAAnimation 获取UIView 对象。我已经实现了以下CAAnimationDelegate 方法

public func animationDidStop(_ animation:CAAnimation, finished:Bool) {
     // Need respective View from "animation:CAAnimation"
}

这个类将执行具有不同视图的多个动画。所以我需要找出在这个委托方法中完成了哪个View的动画。如果有可能从这个动画中获得视图,请指导我。

【问题讨论】:

  • 使用键值编码来携带对动画内部视图的引用。
  • 谢谢马特!它有效。

标签: ios swift uikit caanimation


【解决方案1】:

正如 matt 建议的那样,您可以找到已完成的动画。

首先,您需要在创建动画时为动画添加不同的键值,如下所示:

let theAnimation = CABasicAnimation(keyPath: "opacity")
theAnimation.setValue("animation1", forKey: "id")
theAnimation.delegate = self

let theAnimation2 = CABasicAnimation(keyPath: "opacity")
theAnimation2.setValue("animation2", forKey: "id")
theAnimation2.delegate = self

animationDidStop 方法中你可以识别动画:

func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {

    if let val = anim.value(forKey: "id") as? String {
        switch val {
        case "animation1":
            print("animation1")
        case "animation2":
            print("animation2")
        default:
            break
        }
    }
}

我接受了THIS 的回答,并使用switch 大小写将Objective c 代码转换为swift。

【讨论】:

    【解决方案2】:

    我只是在 UIView 中使用 tag 属性

    animatedView.tag = 10
    
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        for myView in view.subviews {
            if myView.tag == 10 {
                myView.removeFromSuperview()
                return
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多