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 为按钮制作摇动动画


- 网上有没有好的 UIScrollView 教程? 2022-01-01
- URL编码Swift iOS 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- UITextView 内容插图 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- GPS状态的广播接收器? 2022-01-01