ios - Swift Tableview 单元格按钮图像根据 tableview 数据更改
<p><p>我正在尝试解析 JSON 并在 tableview 数组中附加 JSON 响应值。在下面的响应 <code>subcategory</code> 几个对象我得到了值,但其中一些我得到了 null。</p>
<pre><code>{
"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
}
]
}
</code></pre>
<ol>
<li><p>我需要将值附加到数组 <code> 中,例如:</code>。如果子类别 null 意味着我需要存储 null 否则它的值。</p></li>
<li><p>应用到单元格后,如果值为null需要更改单元格按钮图片。</p></li>
</ol>
<p>我尽力解决超出范围的问题,但在上述情况下我没有得到很好的结果。</p>
<p>这是我的代码</p>
<pre><code> if indexPath.row < id.count {
cell.accessibilityValue = String(id) // If the cell.accessibilityValue not null then need to change cell button image.
}
cell.name_Label.text = name
cell.city_Label.text = city
</code></pre>
<p>从 JSON <code>self.id.append(items)</code> 追加的数组。我得到输出 <code>like </code> 但实际结果应该是 <code></code>。数组的长度不正确,如果数据为 null 或 nil,我需要数据为“null”,因为我通过索引获取值,并且每个索引都知道为 null 或具有值,但它必须存在</p ></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><ol>
<li><code>id</code> 应该是 <code>optional Int</code></li> 的数组
<li><p><code>subcategory_id</code> 应该是 <code>optional Int</code></p>
<pre><code>var subcategory_id: Int?
var id: = []
if let subCat = subcategory_id {
id.append(subCat)
}
else {
id.append(nil) // id=
}
</code></pre>
<p>在你的 cellForAtRow 重载中</p>
<p><code>id</code> 是一个 <code>optional Int</code>(<code>Int?</code>) 数组,你必须解开它</p>
<pre><code>cell.id_Label.text = id!
</code></pre>
<p>或</p>
<pre><code>if let i = id {
cell.id_Label.text = "\(i)"
}
else {
print("id is nil")
}
</code></pre> </li>
</ol></p>
<p style="font-size: 20px;">关于ios - Swift Tableview 单元格按钮图像根据 tableview 数据更改,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/51733375/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/51733375/
</a>
</p>
页:
[1]