小编Ahm*_*thi的帖子

替代扩展的方法

我想UIView通过添加一些函数来扩展,并在UIView我想要的任何子类中重写它们。我在苹果文档中发现我无法覆盖扩展(编译器会抱怨),这是有道理的。所以

我需要有人提出以下替代方法:

extension UIView { 
  func hide() { //do almost nothing } 
}

class myLabel: UILabel { 
  override func hide() { 
    //do work on uilabel that can't be done on imgView
  }
}

class myImageView: UIImageView {
 override func hide() { 
    //do work on imgView that can't be done on uilabel
  }
}
Run Code Online (Sandbox Code Playgroud)

我想要这个的原因是,稍后在我的代码中我将面对下面的代码,并且我有很多子类,并且我不想编写太多if-lets尝试将其转换viewmyLabel, myTextView, myImageView... etc

let view = cell.viewWithTag(someTag)
// and I want to write this below without casting …
Run Code Online (Sandbox Code Playgroud)

ios swift swift-extensions swift-protocols

5
推荐指数
1
解决办法
743
查看次数

标签 统计

ios ×1

swift ×1

swift-extensions ×1

swift-protocols ×1