【问题标题】:Swift Tableview cell button image changed based on tableview dataSwift Tableview 单元格按钮图像根据 tableview 数据更改
【发布时间】:2018-08-07 18:37:27
【问题描述】:

我正在尝试解析 JSON 并在 tableview 数组中附加 JSON 响应值。在下面回复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. 我需要将值附加到数组 like : [10, null,....] 中。如果子类别 null 意味着我需要存储 null 否则它的值。

  2. 应用到单元格后,如果值为null需要更改单元格按钮图片。

我已尽力解决超出范围的问题,但在上述情况下我没有得到很好的结果。

这是我的代码

 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 或具有值,但它必须存在

【问题讨论】:

  • 您是否已将项目附加到您的数组中?在这里打印你的数组
  • 更新后请查看。 @ShahzaibQureshi
  • 数组中的每个项目都是一个字符串?还是字典?
  • 它的字符串不是字典@ShahzaibQureshi
  • 然后你可以检查如下: if id[indexPath.row] == null { //setImage }else{ }

标签: ios json swift tableview


【解决方案1】:
  1. id 应该是 optional Int 的数组
  2. 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 重载中

    idoptional 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")
        }
    

【讨论】:

  • 但是当我为单元格标签赋值时,获取 cell.id_Label.text = String(id[indexPath.row]) 错误:无法使用类型为参数列表的“String”类型调用初始化程序(诠释?)'@Hamed Akhlaghi
  • 使用这个“\(id[indexPath.row])”而不是String(id[indexPath.row]),如果没有值,这个代码将添加nil到cell.id_Label.text对于身份证
  • 太好了。但我也得到了结果 Optional(values) cell.id_Label.text = String("(id[indexPath.row])" ),警告字符串插值会为可选值生成调试描述;你的意思是说清楚吗? @Hamed Akhlaghi
  • if (id[indexPath.row]) != nil { cell.id_Label.text = "(id[indexPath.row])!"} else { cell.id_Label.text = ""}您应该打开 (id[indexPath.row]) 或设置默认值
  • 不,它无法获得相同的选项 @Hamed Akhlaghi if (id[indexPath.row]) != nil { cell.id_Label.text = String("(id[indexPath.row])" ) cell.id_Label.textColor = UIColor.red } else { cell.id_Label.text = "" cell.id_Label.textColor = UIColor.green }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
相关资源
最近更新 更多