【问题标题】:Adding an Image into a cell将图像添加到单元格中
【发布时间】:2014-06-07 06:58:31
【问题描述】:

我已经阅读了大量问题,但似乎找不到答案

我有一个 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
}

【问题讨论】:

  • 你能发布你的整个 cellForRowAtIndexPath 函数吗?

标签: uitableview swift xcode6


【解决方案1】:

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

  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
    }

【讨论】:

  • 啊谢谢 :),建议 1 是我的答案的解决方案,Swift 需要一些时间来适应
  • 如何调整单元格大小以适应图像自动约束?
  • 在 Swift 2.1 中也适用于我,感谢简单的解释和解决方案
  • 如果我有自定义图像怎么办,这不起作用,即我无法设置cell.myImage = UIImage(named: "something.png")
【解决方案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
    

【讨论】:

    猜你喜欢
    • 2014-07-11
    • 2011-08-17
    • 2015-11-09
    • 2019-01-02
    • 2021-01-24
    • 2011-07-09
    • 2013-01-11
    • 2011-09-10
    • 2013-05-27
    相关资源
    最近更新 更多