【问题标题】:How to display specific image in tableview in swift 2如何在swift 2中的tableview中显示特定图像
【发布时间】:2016-03-05 16:48:19
【问题描述】:

我想根据获取的 json 数据在 tableview 中显示特定的图像。我的图像位于本地文件夹的资产中。

假设 json 是:

[
{
"name": "john",
"car": "bmw",
},
{
"name": "mike",
"car": "audi",
}
{
"name": "ana",
"car": null,
}
{
"name": "nick",
"car": "mazda",
}
]

我在资产中的图片:

bmw.jpg 
audi.jpg 
nothing.jpg // to display "ana" image

我没有图片mazda.jpg。

属性:

var name: [String] = []
var image: [String] = []

所以我将 json 数据解析为字符串数组...我在表格单元格中遇到问题

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell

let imageName = image[indexPath.row]
cell.imageView.image = UIImage(named: imageName)

我的目标是如果“name”是“john”,则在 tableview 中显示本地图像“bmw”

已编辑:

我设法显示图像,但我将如何处理 null 和“mazda”

我尝试像这样的 switch 语句:

switch imageName {
        case  "" :
        cell.imageLabel.image = UIImage(named: "nothing")
        case imageName:
        cell.imageLabel.image = UIImage(named: imageName)
        case: // need code for all others that I dont have image
        cell.imageLabel.image = UIImage(named: "nothing")
      }

【问题讨论】:

    标签: ios uitableview switch-statement swift2


    【解决方案1】:

    试试这个

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
        let imageName = image[indexPath.row]
        cell.imageView.image = UIImage(named: imageName)
        return cell
    }
    

    【讨论】:

    • 提前编辑文本 tnx
    【解决方案2】:

    此代码将尝试使用图像数组中的名称创建图像,如果创建失败(ana 和 nick 情况),它将使用“nothing”代替。

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
    
        if let imageForRow = UIImage(named: image[indexPath.row]) where indexPath.row >= image.count {
            cell.imageView.image = imageForRow
        } else {
            cell.imageView.image = UIImage(named: "nothing.jpg")
        }
    
        return cell
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多