作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我创建了一个 @IBAction
函数,将 View Controller 中的按钮连接到主 Storyboard。目标是让我的按钮执行摇动动画,但我不知道如何连接它。我在 extension UIButton {
行上收到错误声明仅在文件范围内有效。我需要删除扩展程序吗?移动其他线吗?如何让按钮动画化?下面显示了更多用于运行 Mapkit 的代码,我需要创建另一个类吗?
我尝试完全删除扩展,重命名 UIButton 之前的名称并将 UIButton() 更改为其他名称,尝试查看教程,但没有什么完全适合我所拥有的。
//button
@IBAction func diceButton(_ sender: UIButton) {
//shake button
//shake
extension UIButton {
func buttonshake() {
let shake = CABasicAnimation(keyPath: "position")
shake.duration = 0.1
shake.repeatCount = 2
shake.autoreverses = true
let fromPoint = CGPoint(x: center.x - 5, y: center.y)
let fromValue = NSValue(cgPoint: fromPoint)
let toPoint = CGPoint(x: center.x + 5, y: center.y)
let toValue = NSValue(cgPoint: toPoint)
shake.fromValue = fromValue
shake.toValue = toValue
layer.add(shake, forKey: nil)
}
}
}
错误发生在//shake下的行上,而不是其他地方。这一切都在按钮的操作中,并且我的代码中的任何位置都没有其他按钮,因此我看不到任何可能重复的内容。
最佳答案
您需要将扩展
移动到顶层,超出任何func
或class
定义。
最佳实践是创建一个新文件,将其命名为 UIButton+Shake.swift
,并将您的扩展放入其中。
然后,在IBAction
中,只需调用buttonshake
UIButton+Shake.swift
extension UIButton {
func buttonshake() {
let shake = CABasicAnimation(keyPath: "position")
// And all the other stuff
layer.add(shake, forKey: nil)
}
}
你的 Controller .swift
class YourController : UIViewController {
// ...
@IBAction func diceButton(_ sender: UIButton) {
sender.buttonshake()
}
}
关于ios - 如何让按钮执行动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56991339/
我是一名优秀的程序员,十分优秀!