简体   繁体   English

基于Tableview数据更改了Swift Tableview单元格按钮图像

[英]Swift Tableview cell button image changed based on tableview data

I am trying to parse JSON and appending JSON response value within tableview array. 我正在尝试解析JSON并将JSON响应值附加到tableview数组中。 Here below response subcategory few objects I am getting values but some of them I am getting null. 在下面的响应subcategory一些对象正在获取值,但有些对象却为空。

{
    "category": [
    {
    "id": 0,
    "subcategory": [   //Table cell button need to show green color
    {
    "subcategory_id": 10
    }
    ]
    },
    {
    "id": 0,
    "subcategory": null //Table cell button need to show red color
    }
    ]
}
  1. I need to append the values into array like : [10, null,....] . 我需要将值附加到数组中, like : [10, null,....] if subcategory null means I need to store null otherwise its value. 如果子类别为nu​​ll,则表示我需要存储null,否则需要存储其值。

  2. After applying to cell, If the value is null need to change cell button Image. 应用于单元格后,如果该值为null,则需要更改单元格按钮Image。

I tried my best to resolved out of range but I didn't get well result for above scenario. 我尽力解决了超出范围的问题,但在上述情况下我没有得到很好的结果。

Here is my code 这是我的代码

 if indexPath.row < id.count {
            cell.accessibilityValue = String(id[indexPath.row]) // If the cell.accessibilityValue not null then need to change cell button image.
        }
        cell.name_Label.text = name[indexPath.row]
        cell.city_Label.text = city[indexPath.row]

Array appending from JSON self.id.append(items) . 从JSON self.id.append(items)追加数组。 I am getting output like [10] but actual result should be [10,null] . 我得到like [10]输出,但实际结果应为[10,null] The length of the array which is not right, i need the data to be "null" if it is null or nil because i get values by index and each index is know to be null or with value but it must be there 数组的长度不正确,如果数据为null或nil,则我需要数据为“ null”,因为我通过索引获取值,并且每个索引都知道为null或具有值,但必须存在

  1. id should be an array of optional Int id应该是optional Int数组
  2. subcategory_id should be optional Int subcategory_id应该是optional Int

     var subcategory_id: Int? var id: [Int?] = [] if let subCat = subcategory_id { id.append(subCat) } else { id.append(nil) // id=[nil] } 

    in your cellForAtRow overload 在你的cellForAtRow重载

    id is an array of optional Int ( Int? ) you have to unwrap it id是一个optional IntInt? )数组,您必须将其拆开

     cell.id_Label.text = id[indexPath.row]! 

    or 要么

     if let i = id[indexPath.row] { cell.id_Label.text = "\\(i)" } else { print("id is nil") } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM