gpt4 book ai didi

ios - 如何让按钮执行动画?

转载 作者:行者123 更新时间:2023-11-29 05:36:30 24 4
gpt4 key购买 nike

我创建了一个 @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下的行上,而不是其他地方。这一切都在按钮的操作中,并且我的代码中的任何位置都没有其他按钮,因此我看不到任何可能重复的内容。

最佳答案

您需要将扩展移动到顶层,超出任何funcclass定义。

最佳实践是创建一个新文件,将其命名为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com