我有一个框架,它声明了一个 View Controller 。
这就是使用我的框架的人需要知道的所有细节。
但是,一个实现细节是我的类是基于 UITableViewController 的。
是否可以公开地说我是 UIViewController 的子类,但私下实际上是 UITableViewController 的子类?
最佳答案
不,你不能隐藏你继承自 UITableViewController
如果您向某人展示您的 View Controller (因此您将其公开),那么每个人都会知道它继承自 UITableViewController
。
has-a 而不是 is-a
但是有一个解决方案。正如您可能知道的那样,您可以完全控制自己类的属性。
所以你可以让你的 ViewController
继承自 UIViewController
然后,在你的 ViewController.swift 文件中,定义另一个对象来控制 tableView
.像这样
import UIKit
class ViewController: UIViewController {
private var tableView = UITableView()
private var tableViewController = TableViewController()
public override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = tableViewController
tableView.dataSource = tableViewController
// add your tableView to the current view
}
}
fileprivate class TableViewController: NSObject, UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
fatalError("Implement me")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
fatalError("Implement me")
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// ...
}
}
关于Swift 3 私有(private)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39603583/