我有一个带有两个自定义UITableView
类的UITableViewCell
,我将它们定级并显示在表视图中。
我的情节提要看起来像这样:
以前,我是在数据中进行硬编码的,并且基于UITableView
的indexPath.row
,我将使适当的自定义单元格类出队并加载数据。
一个例子:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
switch (indexPath.row)
{
case 0...9:
let 3Pic = tableView.dequeueReusableCell(withIdentifier: "3PicRow", for: indexPath) as! 3PicRowCell
if indexPath.row == 0
{
3Pic.leftNameLabel.text = "Name"
3Pic.leftPositionLabel.text = "Position"
3Pic.leftImageView.image = UIImage(named: "icon")
3Pic.MidddleNameLabel.text = "Name"
3Pic.MiddlePositionLabel.text = "Position"
3Pic.MiddleImageView.image = UIImage(named: "icon")
3Pic.RightNameLabel.text = "Name"
3Pic.RightPositionLabel.text = "Position"
3Pic.RightImageView.image = UIImage(named: "icon")
}
else if indexPath.row == 1 // row=1 through row=9
{
// Do same thing
}
return 3Pic
case 10...12:
let 2Pic = tableView.dequeueReusableCell(withIdentifier: "2PicRow", for: indexPath) as! 2PicRowCell
if indexPath.row == 10
{
2Pic.leftNameLabel.text = "Name"
2Pic.leftPositionLabel.text = "Position"
2Pic.leftImageView.image = UIImage(named: "icon_about")
2Pic.rightNameLabel.text = "Name"
2Pic.rightPositionLabel.text = "Position"
2Pic.rightImageView.image = UIImage(named: "icon")
}
// Do same thing until row=12
return 2Pic
default:
break;
}
// Will never reach here
return UITableViewCell()
}
现在,我们正在迁移到严格从数据库中获取的数据,我现在很难根据自己获取的数据量来弄清楚如何使适当的单元出队。
JSON数据示例:
{
"item1": {
"id": 1,
"first_name": "First",
"last_name": "Last",
"position": "Position",
"image_url": "icon.com"
},
"item2": {
"id": 2,
"first_name": "First",
"last_name": "Last",
"position": "Position",
"image_url": "icon.com"
},
"item3": {
"id": 3,
"first_name": "First",
"last_name": "Last",
"position": "Position",
"image_url": "icon.com"
}
}
谁能为我的困境提供解决方案?
最佳答案
您可以检查row
JSON数据的键计数。如果您有3个键,请使用3pic
单元格。如果您有2个按键,请使用2pic
单元格。
伪代码如下所示:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let jsonObject = jsonData[indexPath.row]
let keyCount = jsonObject.keys.count
if keyCount == 3 {
3Pic.leftNameLabel.text = "Name"
3Pic.leftPositionLabel.text = "Position"
3Pic.leftImageView.image = UIImage(named: "icon")
3Pic.MidddleNameLabel.text = "Name"
3Pic.MiddlePositionLabel.text = "Position"
3Pic.MiddleImageView.image = UIImage(named: "icon")
3Pic.RightNameLabel.text = "Name"
3Pic.RightPositionLabel.text = "Position"
3Pic.RightImageView.image = UIImage(named: "icon")
} else {
2Pic.leftNameLabel.text = "Name"
2Pic.leftPositionLabel.text = "Position"
2Pic.leftImageView.image = UIImage(named: "icon_about")
2Pic.rightNameLabel.text = "Name"
2Pic.rightPositionLabel.text = "Position"
2Pic.rightImageView.image = UIImage(named: "icon")
}
return cell
}
我确实认为使用集合视图将是一种更清洁的方法。您只需要1个单元格。