arrays - 比较两个 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
}
解决方案
您正在寻找的是一个break
. 一旦你发现key
可用,你需要设置图像并退出。在这里,发生的情况是您设置图像,然后再次检查。实际上,您的图像取决于数组的最后一个元素。
if cell.textLabel?.text == key.key {
cell.imageView!.image = UIImage(named:"red_icon")
break
} else {
cell.imageView!.image = UIImage(named:"green_icon")
}
推荐阅读
- r - R:在特定的行和列上循环自定义函数
- wix - util:RegistrySearch 变量可以与刻录中的 ExePackage 的 SourceFile 一起使用吗?
- excel - 自定义功能区按钮打开宏文件但随后切换焦点
- vba - VBA,如何将函数作为另一个函数的参数传递
- android - 无法使用给定参数调用 requestLocationUpdates
- c# - Swashbuckle - 在招摇文档中将字符串视为枚举
- entity-framework - 实体框架代码第一个一对零或一个具有单独身份的关系
- c# - 我可以在 UWP 应用程序中执行 Python 文件吗?
- c# - Dll 的内部引用在主代码中被破坏
- python - Python:意外的字符串比较结果:真!=真