在同一应用程序中为不同屏幕制作可重用的表格视图的最佳方法是什么?

Jaa*_*rek 4 tableview ios swift swift3

我正在快速开发类似于Instagram的社交ios应用程序。我有2个屏幕,其中包含几乎与提要相同的显示。第一个是包含表视图的简单提要屏幕,第二个是包含配置文件信息的表视图标题的配置文件屏幕,并且该表视图应包含第一个屏幕的相同数据。

我能够做到这一点,但是我不得不在第一屏和第二屏中为tableview重复相同的代码:(cellforRow,Number,数据和计算...)

在这种情况下避免重复数据的最佳方法是什么?

iOS*_*eak 5

您可以通过编写一个单独的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)