单击时查看摇动动画错误

时间:2018-04-28 13:20:03

标签: ios swift swift4

我一直在使用以下UIView扩展来动摇观点:

func shake(count: Float = 4, for duration: TimeInterval = 0.5,
           withTranslation translation: CGFloat = 5) {
    let animation: CABasicAnimation = CABasicAnimation(keyPath: "transform.translation.x")
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
    animation.repeatCount = count
    animation.duration = duration / TimeInterval(animation.repeatCount)
    animation.autoreverses = true
    animation.fromValue = NSValue(cgPoint: CGPoint(x: -translation, y: self.center.y))
    animation.toValue = NSValue(cgPoint: CGPoint(x: translation, y: self.center.y))
    layer.add(animation, forKey: "shake")
}

用法:

view.shake(count: 3, for: 0.2, withTranslation: 8)

这适用于摇动视图(在我的情况下,我正在摇动一些按钮,UIView和一些图像视图)。 当我在摇动动画期间尝试点击其中一个视图时会出现问题。

我收到了:

  

由于未捕获的异常而终止应用   'NSInvalidArgumentException',原因:' - [NSConcreteValue doubleValue]:   无法识别的选择器发送到实例0x600000442640'

如果是按钮,如果我禁用按钮然后启动摇动动画,似乎可以防止发生错误。 不幸的是,这似乎不适用于图像视图和UIViews。

我还禁用了图像视图/ UIView上的用户交互,但无济于事。

我觉得这与在视图动画制作时在点击测试检查期间传递给较低层的错误坐标有关。

对此错误的任何见解将不胜感激。

1 个答案:

答案 0 :(得分:3)

您可以尝试使用此代码。它应该会有所帮助:

extension UIView {

    func shakeByX() {
        let animation = CABasicAnimation(keyPath: "position")
        animation.duration = 0.07
        animation.repeatCount = 3
        animation.autoreverses = true
        animation.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 6, y: self.center.y))
        animation.toValue = NSValue(cgPoint: CGPoint(x: self.center.x + 6, y: self.center.y))
        self.layer.add(animation, forKey: "position")
    }

    func shakeByY() {
        let animation = CABasicAnimation(keyPath: "position")
        animation.duration = 0.07
        animation.repeatCount = 3
        animation.autoreverses = true
        animation.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x, y: self.center.y - 6))
        animation.toValue = NSValue(cgPoint: CGPoint(x: self.center.x, y: self.center.y + 6))
        self.layer.add(animation, forKey: "position")
    }
}