如何在swift 2中在tableview中显示特定图像
问题描述:
我想根据所采用的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")
}
答
试试这个
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
}
答
此代码将尝试从您的图像阵列创建一个名为图像,如果它没有创建一个(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
}
预先编辑文本tnx – Shoody