我为UIButton创建了一个子类,所以我可以点击动画效果,效果起作用,当我尝试将它连接到我的视图控制器中的@IBAction时,它不起作用。该功能未被调用。我将子类设置为记分板中的按钮类。这是我的代码:
import UIKit
class SpringyButton: UIButton {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.layer.transform = CATransform3DMakeScale(0.8, 0.8, 1)
}, completion: nil)
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.layer.transform = CATransform3DMakeScale(1, 1, 1)
}, completion: nil)
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.layer.transform = CATransform3DMakeScale(1, 1, 1)
}, completion: nil)
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.layer.transform = CATransform3DMakeScale(1, 1, 1)
}, completion: nil)
}
}
和我在ViewController中的IBAction:
@IBAction func test(sender: AnyObject) {
println("go")
}
我不确定导致这种情况的原因是什么?
旁注:我已经读过,继承UIButton的子类并不是一个好主意,是否更好地将UIView子类化并用一个轻敲手势识别器来解决这个问题?
感谢。
答案 0 :(得分:1)
问题是您只需覆盖触摸事件。覆盖函数后必须调用super。例如,在下面的touchesBegan
函数中:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.layer.transform = CATransform3DMakeScale(0.8, 0.8, 1)
}, completion: nil)
super.touchesBegan(touches, withEvent: event)
}
像这样你必须为你覆盖的所有触摸事件添加超级。如果您遇到任何问题,请告诉我。
答案 1 :(得分:0)
我相信Interface Builder只使用UIButton。所以子类化确实没有用。如果您真的想使用自定义类,可以通过编程方式创建它。
let myButton : SpringyButton = SpringyButton()
让我知道这是否有效和/或如果那是你想要的东西!