斯威夫特 4.1。您可以创建从 UITableViewDataSource 和 UITableViewDelegate 类继承的单独类。这里我在 DataSource 类中实现 UITableViewDataSource() 方法。你需要继承 NSObject 这样我们就不必摆弄 @objc 和 @class 关键字,因为 UITableViewDataSource 是一个 Objective-C 协议。
import Foundation
import UIKit
class DataSource: NSObject, UITableViewDataSource {
var formData: [FormData]? = nil
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.formData?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
let label = cell?.contentView.viewWithTag(100) as? UILabel
let type = self.formData![indexPath.row]
label?.text = type.placeHolder
return cell!
}
}
现在我们将 DataSource 设置为 UITableView。如果我们创建单独的类,那么我们必须将数据传递给 DataSource 类。
class ViewController: UIViewController {
@IBOutlet weak var tblView: UITableView!
var formData: [FormData]? = nil
var dataSource = DataSource()
override func viewDidLoad() {
super.viewDidLoad()
formData = FormData.array
dataSource.formData = formData // Pass data to DataSource class
tblView.dataSource = dataSource // Setting DataSource
}
}
以类似的方式,您可以在单独的类中实现 UITableViewDelegate。另一种分离 DataSource 和 Delegate 的方法是创建 viewController 的扩展。即使你可以创建单独的类,你只能为你的视图控制器定义扩展。在您定义扩展时,您不需要传递数据。
class ViewController: UIViewController {
@IBOutlet weak var tblView: UITableView!
var formData: [FormData]? = nil
override func viewDidLoad() {
super.viewDidLoad()
formData = FormData.array
tblView.dataSource = self
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.formData?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
let label = cell?.contentView.viewWithTag(100) as? UILabel
let type = self.formData![indexPath.row]
label?.text = type.placeHolder
label?.backgroundColor = UIColor.gray
return cell!
}
}