我的问题与我以前的问题有点相似,但有所不同。
有一个代码描述:我有 2 个 Json 数组,我尝试在我的代码中进行比较 -> all 和 allUrl。当数组 all 包含数组 allUrl 图像表中的某个 id 时,应将行更改为红色,反之亦然为绿色。
还有我的新问题:如何在表格中只显示“red_icon”数据?这两个数组的数据应该相似。谢谢
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
cell.textLabel?.text = all[indexPath.row].id
cell.detailTextLabel?.text = all[indexPath.row].timestampValue
let listOfStudentsUrl = allUrl.reduce(into: [String:String]()){$0[$1.id] = $1.timestampValue}
// Compare data
listOfStudentsUrl.forEach{ key in print(key)
if cell.textLabel?.text == key.key {
cell.imageView!.image = UIImage(named:"red_icon")
break
}else{
cell.imageView!.image = UIImage(named:"green_icon")
}}
return cell
}
在下面讨论后正确的工作代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
let listOfStudentsUrl = allUrl.reduce(into: [String:String]()){$0[$1.id] = $1.timestampValue}
// Compare data
listOfStudentsUrl.forEach{ key in print(key)
if all[indexPath.row].id == key.key {
cell.textLabel?.text = all[indexPath.row].id
cell.detailTextLabel?.text = all[indexPath.row].timestampValue
cell.imageView!.image = UIImage(named:"red_icon")
cell.isHidden = false
break
}else{
cell.isHidden = true
}}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var rowHeight:CGFloat = 0.0
let listOfStudentsUrl = allUrl.reduce(into: [String:String]()){$0[$1.id] = $1.timestampValue}
for key in listOfStudentsUrl{
if all[indexPath.row].id == key.key{
rowHeight = 49.0
break
}else{
rowHeight = 0.0
}}
return rowHeight
}