gpt4 book ai didi

ios - 如何根据 reuseIdentifier 控制我的单元格?

转载 作者:行者123 更新时间:2023-11-28 15:31:06 25 4
gpt4 key购买 nike

我创建了两个不同的单元格以在其中显示不同的数据。我为它们分配了 reuseIdentifier("TableCell""FixtureCell")。他们有两个不同的类,名为 FixtureTableViewCellLeagueTableViewCell

如果单元格标识符是 "TableCell" show TableCell,我想这样做。

否则,如果单元格标识符是 "FixtureCell",则显示 FixtureCell

我该如何控制?

我的代码如下。我只做了 "TableCell"。我不能为另一个做。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tblLeagueTable.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! LeagueTableViewCell

let teams = tableArray[indexPath.row]

cell.lblLeagueTableTeam.text! = teams.teamName
cell.lblOwnGoal.text! = teams.ownGoal
cell.lblScoredGoal.text! = teams.scoredGoal
cell.lblLeagueTableTotalMatch.text! = teams.totalMatch
cell.lblTotalPoints.text! = teams.totalPoint

return cell
}

最佳答案

根据以往的经验,基于IndexPath来实现动态样式并不是一个好主意。我想建议模型驱动的计划。

首先,像这样定义一个模型:

class DemoCellModel: NSObject {
var identifier: String = ""
var classTypeString: String?
var cellData: NSObject?

convenience init(identifier: String, classTypeString: String? = nil, cellData: NSObject? = nil) {
self.init()
self.identifier = identifier
self.classTypeString = classTypeString
self.cellData = cellData
}
}

然后,创建一个模型数组:

var models: [DemoCellModel]  = []

override func viewDidLoad() {
super.viewDidLoad()
guard var bundleName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String else { return }
bundleName = bundleName + "."
models.append(DemoCellModel(identifier: "TableCell", classTypeString: bundleName + "LeagueTableViewCell", cellData: nil))
models.append(DemoCellModel(identifier: "FixtureCell", classTypeString: bundleName + "FixtureTableViewCell", cellData: nil))
}

最后,生成您的自定义单元格:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = models[indexPath.row]
var cell = tableView.dequeueReusableCell(withIdentifier: model.identifier)
if cell == nil {
var cellClassType: UITableViewCell.Type
if let classTypeString = model.classTypeString, let classType = (NSClassFromString(classTypeString) as? UITableViewCell.Type) {
cellClassType = classType
} else {
cellClassType = UITableViewCell.self
}
cell = cellClassType.init(style: .default, reuseIdentifier: model.identifier)
}

if var cell = cell as? testProtocol {
cell.cellData = model.cellData
}

return cell!
}

protocol testProtocol {
var cellData: NSObject? { get set }
}

关于ios - 如何根据 reuseIdentifier 控制我的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44732091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com