swift - 如何重构我的代码以避免重复

标签 swift uibutton uilabel refactoring extension-methods

我有一个函数可以修改 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/

相关文章:

ios - 按下其他按钮后无法更改uibutton的图像

iphone - iOS 5 中 UILabel 的多色

iOS 标签不会在 Swift 中使用函数更新文本

swift - 如何在 UnsafeMutableRawPointer 处初始化内存

ios - Swift 2 结构与数组

ios - 修改 Popover View Controller 的宽度

ios - 将 uilabel 和 uiimageview 保存为 uiimage

ios - 推送通知 - 当应用程序从后台关闭时设置 rootViewController

iphone - 单击时如何使自定义按钮键像iPhone按钮键一样大

objective-c - 将对象添加到 NsMutableArray 取决于选中的复选框数量