我创建了一个自定义按钮类,它是UIButton的子类, 并编写一个UIButton扩展。
这是我的扩展名:
extension UIButton {
func setButtonCurvy() {
self.layer.cornerRadius = self.frame.size.height/2
}
//This function should be run when button tapped
func buttonTapped(_ completion: @escaping () -> Void) {
let anim = CASpringAnimation(keyPath: "transform.scale")
anim.fromValue = 0.9
anim.toValue = 1.1
anim.timingFunction = CAMediaTimingFunction(name: .easeIn)
anim.autoreverses = true
anim.repeatCount = 0
anim.duration = 1
self.layer.add(anim, forKey: nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.9) {
completion()
}
}
}
我的课是:
class MyButton: UIButton {
//Customize buttons...
override func awakeFromNib() {
self.setButtonCurvy()
self.backgroundColor = UIColor.mainButtonColor()
switch self.tag {
case 1:
self.titleLabel?.font = UIFont(name: "Mostley Script", size: 23)
break
case 2:
self.titleLabel?.font = UIFont(name: "Mostley Script", size: 20)
break
default:
self.titleLabel?.font = UIFont(name: "Mostley Script", size: 38)
break
}
}
}
这是我的问题,我在文档中找不到,并提出了问题。也许我只是想念一些显而易见的事情。 每当我的按钮被点击时,有什么方法可以调用buttonHitted()函数吗?
答案 0 :(得分:0)
@AtulParmar的@SaidAlır回答很好,但是如果仅在特定事件类型的情况下(例如(touchUpInside))需要制作动画,请尝试以下解决方案。
import UIKit
class MyButton: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
self.addTarget(self, action: #selector(MyButton.touchUpInside), for: .touchUpInside)
}
@objc func touchUpInside() {
//Perform you animations here
}
}