26

我已阅读大量问题,但似乎无法找到答案

我有一个 TableView 但无法将图像添加到我的单元格

cell.imageView.image = UIImage(named: "osx_design_view_messages")

这段代码应该可以工作,因为我基本上是从问题的答案中复制了它,但由于某种原因它不起作用。有什么建议么?

顺便说一句,我正在使用 swift

 override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
    let cellIdentifier = "cell"

    var cell : UITableViewCell

    cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell
    cell.textLabel.text = self.recipies[indexPath.row]
    var image : UIImage = UIImage(named: "osx_design_view_messages")
    return cell
}
4

2 回答 2

41

以下是您的问题的几个可能原因:

  1. 单元原型需要包含一个 UIImageView。如果您使用的是故事板,请选择单元原型并确保其样式在属性检查器(右侧面板)中设置为“基本”。

  2. 单元格标识符与在情节提要中为原型单元格键入的标识符不匹配。确保在属性检查器中也为“标识符”输入了“单元格”。

  3. 图像未正确从文件加载。要对此进行测试,请在初始化图像后添加以下行:

    println("The loaded image: \(image)")

检查故事板中是否设置了所有内容后,尝试使用以下代码运行它:

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
    {
        let cellIdentifier = "cell"

        var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell

        cell.textLabel.text = self.recipes[indexPath.row]

        var image : UIImage = UIImage(named: "osx_design_view_messages")
        println("The loaded image: \(image)")
        cell.imageView.image = image

        return cell
    }
于 2014-06-07T07:22:00.483 回答
2

斯威夫特 3

// 如果您的图像在服务器上,我们将使用它。

// 我们从一个 url 获取图像。

// 你可以从你的 Xcode 中设置图像。

// 它正在使用为 imageView 分配一个标签

  1. 图片的 URL 在数组中 name = thumbnail 即 self.thumbnail[indexPath.row]
  2. 在 UITableviewCell 上将 imageView 放在单元格上
  3. 选择 UIimageView 从情节提要中为其分配一个标签。

    let pictureURL = URL(string: self.thumbnail[indexPath.row])!
    let pictureData = NSData(contentsOf: pictureURL as URL)
    let catPicture = UIImage(data: pictureData as! Data)
    var imageV = UIImageView()
    imageV = cell?.viewWithTag(1) as! UIImageView
    imageV.image = catPicture
    
于 2017-03-27T12:10:46.323 回答