您可以通过编写一个单独的tableview委托和数据源处理程序类来实现此目的,该类可以处理代表视图控制器显示的数据。
处理程序:
import UIKit
class GenericDataSource: NSObject {
let identifier = "CellId"
var array: [Any] = []
func registerCells(forTableView tableView: UITableView) {
tableView.register(UINib(nibName: "", bundle: nil), forCellReuseIdentifier: identifier)
}
func loadCell(atIndexPath indexPath: IndexPath, forTableView tableView: UITableView) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
return cell
}
}
// UITableViewDataSource
extension GenericDataSource: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return self.loadCell(atIndexPath: indexPath, forTableView: tableView)
}
}
// UITableViewDelegate
extension GenericDataSource: UITableViewDelegate {
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
protocol GenericDataSourceDelegate: class {
// Delegate callbacks methods
}
Run Code Online (Sandbox Code Playgroud)
如何与视图控制器一起使用!
class MyViewControllerA: UIViewController {
@IBOutlet weak var tableView: UITableView!
var dataSource = GenericDataSource()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self.dataSource
self.tableView.dataSource = self.dataSource
}
}
class MyViewControllerB: UIViewController {
@IBOutlet weak var tableView: UITableView!
var dataSource = GenericDataSource()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self.dataSource
self.tableView.dataSource = self.dataSource
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2407 次 |
| 最近记录: |