简体   繁体   中英

Swift Tableview cell button image changed based on tableview data

I am trying to parse JSON and appending JSON response value within tableview array. Here below response subcategory few objects I am getting values but some of them I am getting null.

{
    "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,....] . if subcategory null means I need to store null otherwise its value.

  2. After applying to cell, If the value is null need to change cell button 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) . I am getting output like [10] but actual result should be [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

  1. id should be an array of optional Int
  2. subcategory_id should be 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

    id is an array of optional Int ( Int? ) you have to unwrap it

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

    or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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