[英]Swift Tableview cell button image changed based on tableview data
我正在嘗試解析JSON並將JSON響應值附加到tableview數組中。 在下面的響應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
}
]
}
我需要將值附加到數組中, like : [10, null,....]
。 如果子類別為null,則表示我需要存儲null,否則需要存儲其值。
應用於單元格后,如果該值為null,則需要更改單元格按鈕Image。
我盡力解決了超出范圍的問題,但在上述情況下我沒有得到很好的結果。
這是我的代碼
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]
從JSON self.id.append(items)
追加數組。 我得到like [10]
輸出,但實際結果應為[10,null]
。 數組的長度不正確,如果數據為null或nil,則我需要數據為“ null”,因為我通過索引獲取值,並且每個索引都知道為null或具有值,但必須存在
id
應該是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] }
在你的cellForAtRow重載
id
是一個optional Int
( Int?
)數組,您必須將其拆開
cell.id_Label.text = id[indexPath.row]!
要么
if let i = id[indexPath.row] { cell.id_Label.text = "\\(i)" } else { print("id is nil") }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.