我有一个函数可以修改 UILabel 的文本并用它做一些事情。 为此,我在 UILabel 扩展中创建了我的函数。 效果很好
extension UILabel {
let replaced = self.text.doSomething()
func animate() {
UIView.transition(with: self, duration: duration,options:[], animations: {
self.text = replaced
}
}
}
我需要完全相同的东西,但用于 UIButton 的文本。
有没有办法不在 UIButton Extension 中复制相同的代码?
最佳答案
制定协议(protocol)怎么样?
protocol AnimationProtocol {}
class SomeUIButton: UIButton, AnimationProtocol {}
class SomeUILabel: UILabel, AnimationProtocol {}
extension AnimationProtocol {
let replaced = self.text.doSomething()
func animate() {
UIView.transition(with: self, duration: duration,options:[], animations: {
self.text = replaced
}
}
}
关于swift - 如何重构我的代码以避免重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51287183/