简体   繁体   English

如何在Swift 2的TableView中显示特定图像

[英]How to display specific image in tableview in swift 2

I want to display specific image in tableview depending on json data taken. 我想根据获取的json数据在tableview中显示特定图像。 My images are in assets on local folder. 我的图像在本地文件夹中的资产中。

Let say json is: 假设json是:

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

My images in assets: 我的资产图片:

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

I dont have image mazda.jpg. 我没有图像mazda.jpg。

Property: 属性:

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

So I parse json data into array of strings... and I am having problem in table cells 所以我将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)

My goal is if "name" is "john" display local image "bmw" in tableview 我的目标是,如果“名称”为“ john”,则在表视图中显示本地图像“ bmw”

EDITED: 编辑:

I managed to display image, but what will I do with null and "mazda" 我设法显示了图像,但是如何处理null和“ mazda”

I try switch statement like: 我尝试像这样的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")
      }

Try this 尝试这个

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
}

This code will try to create an image with the name from your image array, and if it fails to create one (the ana and nick cases) it will use "nothing" instead. 此代码将尝试使用图像数组中的名称创建一个图像,如果未能创建一个图像(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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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