是否可以扩展UIButton,使它们都有默认行为,而不使用@IBActions



这可能是一个愚蠢的问题,但我正在思考是否有更好的方法来做到这一点。如果我有10个ViewControllers,每个都有一个不同的按钮(假设这些按钮在故事板中创建了Segues(,但我希望所有这些按钮在点击时都有简单的效果,我会写这样的东西:

首先,UIButton的一个扩展,这样它就有了一个处理动画的方法

extension UIButton {
func tap(){
UIButton.animate(withDuration: 0.05, 
animations: { self.alpha -= 0.1 },
completion: { finish in
UIButton.animate(withDuration: 0.1, animations: {
self.alpha += 0.1
})
})
}

然后为每个ViewController执行一个IBAction。

class FirstViewController: UIViewController {
@IBOutlet weak var button: UIButton!
@IBAction func buttonTouchUpInside(_ sender: Any) {
button.tap()
}
}
...
class TenthViewController: UIViewController {
@IBOutlet weak var button: UIButton!
@IBAction func buttonTouchUpInside(_ sender: Any) {
button.tap()
}    
}

我想知道是否有更好的方法。以某种方式扩展UIButton,使所有UIButton都调用tap((。我需要为所有这些添加一个目标吗?如果我真的使用@IBAction,以后会被它覆盖吗?

提前谢谢,如果这是一个愚蠢的问题,我很抱歉。

我建议创建子类而不是扩展。例如,如果我想有几个按钮,可以在触摸时改变字母或比例,我会使用这样的东西:

class CustomButton: UIControl {
override open var isHighlighted: Bool {
didSet {
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut, animations: {
self.titleLabel.alpha = self.isHighlighted ? 0.3 : 1
self.transform = self.isHighlighted ? .init(scaleX: 0.98, y: 0.98) : .identity
}, completion: nil)
}
}
}

您可以在isHighlighted中指定该效果。你可以制作UIButton的子类或使用UIControl,这样你就可以添加自定义标题标签、imageView等。这取决于你的用例:(

您可以将UIButton子类化并添加自定义行为:

//  MARK: Selection Animated Button
/**
A button which animates when tapped.
*/
open class AnimatedButton: UIButton {
override public var isHighlighted: Bool {
get { super.isHighlighted }
set {
if newValue && !isHighlighted {
UIView.animate(withDuration: 0.05,
animations: { self.alpha = 0.5 },
completion: { finish in
UIButton.animate(withDuration: 0.1, animations: {
self.alpha = 1.0
})
})
}
super.isHighlighted = newValue
}
}
}

最新更新