要将UITableView中属于模型数组对象的数组中的数据显示给tableView,可以按照以下步骤进行:
示例代码如下:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var modelArray: [Model] = [] // 模型数组对象的数组
override func viewDidLoad() {
super.viewDidLoad()
// 初始化模型数组对象的数组
modelArray = [Model1(), Model2(), Model3()]
let tableView = UITableView(frame: view.bounds, style: .plain)
tableView.dataSource = self
tableView.delegate = self
view.addSubview(tableView)
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return modelArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return modelArray[section].dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell
let model = modelArray[indexPath.section]
let data = model.dataArray[indexPath.row]
cell.titleLabel.text = data.title
cell.subtitleLabel.text = data.subtitle
return cell
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// 处理用户点击某一行的操作
}
}
class Model {
var dataArray: [Data] = []
}
class Model1: Model {
override init() {
super.init()
dataArray = [Data(title: "Title1", subtitle: "Subtitle1"), Data(title: "Title2", subtitle: "Subtitle2")]
}
}
class Model2: Model {
override init() {
super.init()
dataArray = [Data(title: "Title3", subtitle: "Subtitle3"), Data(title: "Title4", subtitle: "Subtitle4")]
}
}
class Model3: Model {
override init() {
super.init()
dataArray = [Data(title: "Title5", subtitle: "Subtitle5"), Data(title: "Title6", subtitle: "Subtitle6")]
}
}
class Data {
var title: String
var subtitle: String
init(title: String, subtitle: String) {
self.title = title
self.subtitle = subtitle
}
}
class CustomTableViewCell: UITableViewCell {
let titleLabel = UILabel()
let subtitleLabel = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
titleLabel.frame = CGRect(x: 20, y: 10, width: 200, height: 20)
subtitleLabel.frame = CGRect(x: 20, y: 30, width: 200, height: 20)
contentView.addSubview(titleLabel)
contentView.addSubview(subtitleLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
在上述示例代码中,模型数组对象的数组包含了三个模型对象,每个模型对象都有一个dataArray属性,存储了对应的数据。在cellForRowAtIndexPath方法中,根据indexPath获取对应的模型对象和数据,并将数据显示在自定义的UITableViewCell的子类中。
领取专属 10元无门槛券
手把手带您无忧上云