首页 > 解决方案 > 比较两个 json 数组后的正确图像有时不显示

问题描述

我有 2 个 Json 数组,我尝试在我的代码中进行比较 -> all 和 allUrl。当数组 all 包含数组 allUrl 图像表中的某个 id 时,应将行更改为红色,反之亦然为绿色。但有时工作正常,表格行中的红色图像显示正确,但有时不正确。

这部分有我的代码:

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")
        }else{
        cell.imageView!.image = UIImage(named:"green_icon")
    }}
        return cell
    }

标签: arraysjsonswiftcompare

解决方案


您正在寻找的是一个break. 一旦你发现key可用,你需要设置图像并退出。在这里,发生的情况是您设置图像,然后再次检查。实际上,您的图像取决于数组的最后一个元素。

if  cell.textLabel?.text == key.key {
    cell.imageView!.image = UIImage(named:"red_icon")
    break
} else {
    cell.imageView!.image = UIImage(named:"green_icon")
}

推荐阅读