2016-03-05 100 views
2

我想根據所採用的json數據在tableview中顯示特定圖像。我的圖像位於本地文件夾的資產中。如何在swift 2中在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) 

我的目標是,如果「名」是「約翰在實現代碼如下

「顯示本地圖像‘寶馬’編輯:

我設法顯示圖像,但什麼我會做的空,「馬自達」

我嘗試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") 
     } 

回答

0

試試這個

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 
} 
+0

預先編輯文本tnx – Shoody

0

此代碼將嘗試從您的圖像陣列創建一個名爲圖像,如果它沒有創建一個(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 
}