【问题标题】:Best approach for reusable swift code UIKit可重用 swift 代码 UIKit 的最佳方法
【发布时间】:2019-09-10 23:52:27
【问题描述】:

我看不到 Xcode/Swift 中可重用故事板模式的实用方法。我有许多具有几乎相同行为和外观的 ViewController。所以 viewDidLoad() 总是一样的:

 override func viewDidLoad() {
    super.viewDidLoad()

    labelKESumme.text = something
}

因为每个 ViewController 都必须配置有自己的类,而且 Swift 缺乏多重继承,所以我尝试创建这样的扩展:

extension UIViewController {
  func show() {
    self.labelKESumme.text = something <== ... has no member
  }
}

但由于“没有成员”错误,这不起作用。此外,无法在标签和扩展代码之间配置插座。需要一种方法来配置多个具有相同内容的视图控制器,而无需重复代码。

【问题讨论】:

  • 我喜欢评论lacks the multi inheritance

标签: swift xcode


【解决方案1】:

您可以使用如下协议扩展

// protocol 
protocol Showable {
   var labelKESumme: UILabel?
   func show()
}

//protocol extension if you want same functionality everywhere
extension Showable {
func show() {
      labelKESumme?.text = something
   }
}

// just conform the the protocol
ABCViewController: Showable {
}

// just conform the the protocol
XYZViewController: Showable {
}

// In some code where you have viewController as UIViewController and you know
// that this object conforms to Showable protocol then you can do like this
guard let showable = viewController as? Showable {
    return
}

showable.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    • 2020-09-30
    相关资源
    最近更新 更多