How do you make a shake animation for a button using Swift 3(如何使用 Swift 3 为按钮制作摇动动画)
问题描述
我有一个每 3 秒调用一次的函数.如何为左右晃动的按钮制作晃动动画.
I have a function that gets called every 3 seconds. How can I make a shaking animation for the button that shakes side to side.
func shakeButton() {
if opened == false {
//Shake Animation
}
}
推荐答案
如果我理解正确,请在摇动动画上试试这个.只需在您的 UIButton 子类中使用此方法
if I understood you correctly, try this on shake animation. Simply use this method in your UIButton subclass
class CustomButton: UIButton {
func shake() {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = 0.6
animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
layer.add(animation, forKey: "shake")
}
}
然后您在代码或故事板/xib 中的某处创建 CustomButton
并调用 myButton.shake()
Then you create CustomButton
somewhere in code or storyboard/xib and call myButton.shake()
您可以根据需要简单地采用此解决方案
You can simply adopt this solution on your needs
UPD:我有编辑示例而不是完全符合您的需求
UPD: I have edit example than exactly fitted your needs
UPD2:另一种解决方案只需创建 UIButton
扩展
UPD2: another one solution
Just create UIButton
extension
extension UIButton {
func shake() {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = 0.6
animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
layer.add(animation, forKey: "shake")
}
}
ans 使用你的按钮操作回调:
ans use on you button action callback:
@IBAction func shake(_ sender: UIButton) {
sender.shake()
}
这篇关于如何使用 Swift 3 为按钮制作摇动动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Swift 3 为按钮制作摇动动画


基础教程推荐
- AdMob 广告未在模拟器中显示 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01