在swift(iOS)中设置按钮动画时,如何移动按钮目标/手势识别器



我以迅疾的方式为一些按钮设置动画,使其永远在视图中随机移动,但按钮的"目标"不会移动。要单击该按钮,您必须单击创建该按钮的原始位置,即使它可能在屏幕的另一侧。

有人有关于如何用按钮移动按钮目标的简单说明吗?

func circlePath(view: UIButton, pathDuration: Double){
//create an animation to follow a circular path
let pathAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position")
//interpolate the movement to be more smooth
pathAnimation.calculationMode = kCAAnimationPaced
pathAnimation.repeatCount = .infinity
//no ease in/out to have the same speed along the path
pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
//the paths circular animation is proportional its size
pathAnimation.duration = pathDuration
//The circle to follow will be inside the circleContainer frame.
//it should be a frame around the center of your view to animate.
//do not make it to large, a width/height of 3-4 will be enough.
let curvedPath: CGMutablePathRef = CGPathCreateMutable()
let circleContainer: CGRect = CGRectInset(view.frame, 23, 23)
CGPathAddEllipseInRect(curvedPath, nil, circleContainer)
//add the path to the animation
pathAnimation.path = curvedPath
//add animation to the view's layer
view.layer.addAnimation(pathAnimation, forKey: "myCircleAnimation")
}

不要用"目标"这个词来指点击响应的区域。"目标"对按钮有特定的含义,但事实并非如此。

让我们称之为"命中矩形"。

核心动画实际上并不会在屏幕上为对象设置动画。它创建了一个"表示层",使对象看起来像在移动,但对象本身没有动画。

因此,在动画中"飞行途中"时,不能让按钮对敲击做出响应。

相反,您要做的是在超视图(或包含正在设置动画的层的层,如果您正在执行CAAnimation。)上放置一个敲击手势识别器。然后,您可以使用动画层的表示层的hitTest方法来测试敲击是否在正在设置动画层的边界内。

我在github上有一个项目展示了这种技术。它被称为iOS CAAnimation group demo(链接。)它是用Objective-C编写的,但无论语言如何,技术都是一样的,所以它应该让你知道如何进行。

最新更新